Arrays
There are two types of arrays in Solidity:
Fixed arrays
Dynamic arrays
// Array with a fixed length of 2 elements:
uint[2] fixedArray;
// another fixed Array, can contain 5 strings:
string[5] stringArray;
// a dynamic Array - has no fixed size, can keep growing:
uint[] dynamicArray;You can also create an array of structs:
People[] public people; // dynamic Array, we can keep adding to itRemember that state variables are stored permanently in the blockchain. So creating a dynamic array of structs like this can be useful for storing structured data in your contract, kind of like a database.
Public Arrays
You can declare an array as public, and Solidity will automatically create a getter method for it. The syntax looks like:
struct People {
uint age;
string name;
}
People[] public people;Working with Arrays
Create new People and add them to our people array.
We can also combine these together and do them in one line of code to keep things clean:
Note that array.push() adds something to the end of the array, so the elements are in the order we added them. See the following example:
Example
Examples - Removing array element
Last updated