0

Why can't I initialize storage arrays when declaring them rather than initializing them in function or constructor?

example: this does not work, it amounts to [0, 0, 0, 0]

contract Example {
   uint256[4] array = [1, 2, 3, 4];
   ...
   constructor () {}
}

this does work

contract Example {
   uint256[4] array;
   ...
   constructor () {
      array[0] = [1];
      array[1] = [2];
      ...
   }
}

2 Answers 2

0

You can initialize the storage array like state variable.

Your code works!

To see the values inside your array you can add this function in your contract:

function getArray(uint index) external view returns(uint256){
       return array[index];
}

Now, you must to compile the contract, and put the position index of array that you want the value and it will return the value.

UPDATED ANSWER: For initialize state variable, you must use the following statement:

uint256[4] array = [[VALUE_INDEX_0], [VALUE_INDEX_1], [VALUE_INDEX_2], [VALUE_INDEX_3]];

You must to use only the statement above if you want to initialize and array like state variable. But in a function or constructor you can the statement above or you can access at single index of array and pass it the value. Ex.:

array[0] = 10;
array[1] = 20;
9
  • I'm not sure your example of initializing it in storage works, could you maybe write an example of initializing it with real values?
    – mmmmdev
    Commented Mar 25, 2022 at 15:27
  • This is an example of initializing values in storage array variable: uint256[4] array = [0, 1, 2, 3]; Commented Mar 25, 2022 at 15:38
  • Ok, but that doesn't work.
    – mmmmdev
    Commented Mar 25, 2022 at 15:42
  • You must to insert the instruction below the keyword contract. And to retrieve the array values you can use the function that I wrote above. I tried and it works. Can you expalin better what is the problem? Commented Mar 25, 2022 at 15:45
  • Yes of course... initializing it like you've mentioned: uint256[4] array = [[VALUE_INDEX_0], [VALUE_INDEX_1], [VALUE_INDEX_2], [VALUE_INDEX_3]]; simply doesnt work and initializes it to [0, 0, 0, 0]
    – mmmmdev
    Commented Mar 25, 2022 at 15:57
0

Your code works perfectly fine!
I added a view function getArray() to get your storage array.

contract Example {
   uint256[4] array = [1, 2, 3, 4];

   constructor () {}

    function getArray() external view returns(uint256[4] memory) {
       return array;
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.