Arrays in Solidity
Arrays in Solidity
As we know Solidity is similar to languages like Javascript and Python. Hence, datatypes in Solidity are quite like Javascript. Unlike Javascript, Solidity is a statically typed language. A statically typed language means that you have to specify the data type of any variable before assigning it a value, this is similar to how languages like Java work where we have to specify the type of data of the value in the variable. So, if we want to assign the value of an integer to a variable, we have to define the variable with the data type ‘int’. The same is the case with defining an Array in Solidity as well, you will have to define the array before assigning it a variable. Let's take a look at how variables work in Solidity.
To create an Array in Solidity, the datatype of the Array and the number of elements you want to have in them should be specified. Obviously, the datatype should be something that Solidity accepts and the number of elements you want in the Array should be a positive integer.
You can create an Array by using the following syntax:
<data type> <array name>[size] = <values>
The size of the Array should always be predefined. The number of elements should not exceed the size which has been defined. If the Array size is not defined, Solidity will just set it to how many ever elements you have assigned to the variable.
Here's how to create an Array with a predefined size in Solidity:
pragma solidity ^ 0.8.4
contract arrayExample {
uint[5] public arr2 = [1, 2, 3, 4, 5];
}
If you have any questions, you can find me on my Twitter and LinkedIn