AndCode
AndCode

Reputation: 488

Why string array initialization with literals is so complicated in Solidity?

Still struggling to understand why this is not working in Solidity:

string[] memory testArray;

testArray = ["a", "b"];

I've tried the following and it compiles:

string[] memory testArray1;

testArray1 = new string[](1);
testArray1[0] = "a";
testArray1[1] = "b";

Why am I able to assign more elements to the array testArray1 above despite declaring it of length 1?

Why can't we use push() on string arrays in Solidity?

What is the proper way to assign string literals to string arrays in Solidity? The documentation doesn't prescribe on this and I couldn't find relevant examples elsewhere.

Upvotes: 0

Views: 255

Answers (1)

Antonio Carito
Antonio Carito

Reputation: 1387

Why am I able to assign more elements to the array testArray1 above despite declaring it of length 1?

Because when compiler checks your code, it control only the syntax not your logic. Thus, if you run the second code that you shared in your issue Solidity will give you an error that said: "The array length is 1 but you stored more elements inside it".

Why can't we use push() on string arrays in Solidity?

You can use push() method only for storage array. Otherwise, for memory array you must use indexes to put inside them the relative values. The Solidity documentation say this:

Memory arrays with dynamic length can be created using the new operator. As opposed to storage arrays, it is not possible to resize memory arrays (e.g. the .push member functions are not available). You either have to calculate the required size in advance or create a new memory array and copy every element.

More information about this topic here.

What is the proper way to assign string literals to string arrays in Solidity?

It depends. If you're implementing a storage string array, use push() method in this way:

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.13;
    
contract Array {
    string[] public myArray;

    function fillArrayMemory(string memory _word) public {
        myArray.push(_word);
    }
    
}

If you're implementing a memory array, you must use indexes for put a specific value inside them. Example:

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.13;
    
contract Array {

    function fillArrayMemory() public {
        string[] memory _array = new string[](2);
        _array[0] = "test";
        _array[1] = "test1";
    }
    
}

Upvotes: 2

Related Questions