Table of Contents
In Solidity, structs allow developers to define custom data types composed of multiple fields. These fields can include arrays, enabling the creation of more complex data structures. Let’s explore how to initialize an array inside a struct with an example.
Struct definition with single-dimensional array
First, we’ll define a struct containing an array as one of its fields. Suppose we want to create a struct representing a student, including their name and an array of exam scores. Here’s how we can define such a struct:
pragma solidity ^0.8.0;
contract StudentContract {
struct Student {
string name;
uint[] examScores;
}
}
In this example, the Student
struct consists of two fields: name
, which is a string representing the student’s name, and examScores
, which is an array of unsigned integers representing the student’s exam scores.
🔥 Check this course out: Create Your Own Ethereum Token in Just 30 Mins
Initializing the struct with an array
Now, let’s create a function to initialize a Student
struct with sample data, including an array of exam scores. We’ll add a function addStudent()
to our contract:
pragma solidity ^0.8.0;
contract StudentContract {
struct Student {
string name;
uint[] examScores;
}
Student[] public students;
function addStudent(string memory _name, uint[] memory _scores) public {
students.push(Student(_name, _scores));
}
}
In this code, the addStudent()
function takes two parameters: _name
, representing the student’s name, and _scores
, representing an array of exam scores. It then creates a new Student
struct with the provided data and adds it to the students
array.
Accessing student data
We can also create functions to retrieve and manipulate student data. For example, to get the name and exam scores of a specific student, we can add a function getStudent(uint _index)
:
pragma solidity ^0.8.0;
contract StudentContract {
struct Student {
string name;
uint[] examScores;
}
Student[] public students;
function addStudent(string memory _name, uint[] memory _scores) public {
students.push(Student(_name, _scores));
}
function getStudent(uint _index) public view returns (string memory, uint[] memory) {
require(_index < students.length, "Index out of bounds");
return (students[_index].name, students[_index].examScores);
}
}
This function takes an index _index
as input and returns the name and exam scores of the student at that index in the students
array.
Usage example
Now, let’s demonstrate how to use our contract:
pragma solidity ^0.8.0;
contract StudentContract {
struct Student {
string name;
uint[] examScores;
}
Student[] public students;
function addStudent(string memory _name, uint[] memory _scores) public {
students.push(Student(_name, _scores));
}
function getStudent(uint _index) public view returns (string memory, uint[] memory) {
require(_index < students.length, "Index out of bounds");
return (students[_index].name, students[_index].examScores);
}
}
contract ExampleUsage {
StudentContract studentContract;
constructor() {
studentContract = new StudentContract();
}
function addStudentAndRetrieveData() public {
uint[] memory scores = new uint[](3);
scores[0] = 90;
scores[1] = 85;
scores[2] = 95;
studentContract.addStudent("Alice", scores);
(string memory name, uint[] memory retrievedScores) = studentContract.getStudent(0);
// Now 'name' will be "Alice" and 'retrievedScores' will be [90, 85, 95]
}
}
In this example, we first create a new student with three exam scores and then retrieve the student’s data to verify its correctness.
🔥 Check this course out: Build a One Piece Personality dApp With Solidity
Let’s explore how to initialize a multi-dimensional array inside a struct with a separate example.
Struct definition with multi-dimensional array
We’ll define a struct representing a matrix, which includes a multi-dimensional array to hold its elements. Here’s how the struct is defined:
pragma solidity ^0.8.0;
contract MatrixContract {
struct Matrix {
uint[][] data;
}
}
In this example, the Matrix
struct contains a field named data
, which is a two-dimensional array representing the matrix elements.
Initializing the struct with the multi-dimensional array
Next, we’ll create a function to initialize a Matrix
struct with sample data, including a multi-dimensional array. We’ll add a function createMatrix()
to our contract:
pragma solidity ^0.8.0;
contract MatrixContract {
struct Matrix {
uint[][] data;
}
function createMatrix() public pure returns (Matrix memory) {
uint[][] memory matrixData = new uint[][](3);
for (uint i = 0; i < 3; i++) {
matrixData ;
for (uint j = 0; j < 3; j++) {
matrixData[i][j] = i * 3 + j;
}
}
return Matrix(matrixData);
}
}
In this code, the createMatrix()
function initializes a 3×3 matrix with sequential numbers. It first allocates memory for the outer array, then allocates memory for each inner array, and finally fills in the elements with sequential values.
Accessing matrix data
To access the data stored in the matrix, we can add a function getElement()
:
pragma solidity ^0.8.0;
contract MatrixContract {
struct Matrix {
uint[][] data;
}
function createMatrix() public pure returns (Matrix memory) {
uint[][] memory matrixData = new uint[][](3);
for (uint i = 0; i < 3; i++) {
matrixData ;
for (uint j = 0; j < 3; j++) {
matrixData[i][j] = i * 3 + j;
}
}
return Matrix(matrixData);
}
function getElement(Matrix memory _matrix, uint _row, uint _column) public pure returns (uint) {
return _matrix.data[_row][_column];
}
}
This function getElement()
takes a Matrix
struct as input along with row and column indices and returns the element at the specified position in the matrix.
Usage example
Now, let’s demonstrate how to use our contract:
pragma solidity ^0.8.0;
contract MatrixContract {
struct Matrix {
uint[][] data;
}
function createMatrix() public pure returns (Matrix memory) {
uint[][] memory matrixData = new uint[][](3);
for (uint i = 0; i < 3; i++) {
matrixData ;
for (uint j = 0; j < 3; j++) {
matrixData[i][j] = i * 3 + j;
}
}
return Matrix(matrixData);
}
function getElement(Matrix memory _matrix, uint _row, uint _column) public pure returns (uint) {
return _matrix.data[_row][_column];
}
}
contract ExampleUsage {
MatrixContract matrixContract;
constructor() {
matrixContract = new MatrixContract();
}
function createAndRetrieveMatrixElement() public view returns (uint) {
MatrixContract.Matrix memory matrix = matrixContract.createMatrix();
return matrixContract.getElement(matrix, 1, 2); // Returns the element at row 1, column 2 (5)
}
}
In this example, we first create a new matrix using the createMatrix()
function and then retrieve an element from the matrix using the getElement()
function to verify its correctness.
🔥 Check this course out: Build Hogwarts Sorting Hat dApp on Polygon
Conclusion
Initializing an array inside a struct in Solidity allows developers to create more sophisticated data structures to suit their needs. By incorporating arrays into structs, developers can build contracts capable of managing complex data efficiently. The example provided demonstrates how to define a struct with an array, initialize it with sample data, and retrieve information stored within it.
Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.
Follow us on –
🔮Twitter – https://twitter.com/0xmetaschool
🔗LinkedIn – https://www.linkedin.com/company/0xmetaschool/