Jay Vyas
Jay Vyas

Reputation: 2710

Dynamic array in Solidity

I want to declare a simple array (dynamic list), one set function to push a string in and one get function which returns all the strings saved in the dynamic array.

I search a lot but not able to find this simple stuff.

Upvotes: 3

Views: 10177

Answers (2)

saman.shahmohamadi
saman.shahmohamadi

Reputation: 485

If, finally, you want to interact with your smart contract with tools like web3j (for java) or web3js (javascript) in an application, working with dynamic arrays is not going to work because of some bugs in those libraries.
In this case you should serialize your output array. Same applies if you have an input array.

Upvotes: 4

Yegor
Yegor

Reputation: 3950

Here is my solution, you need experimental ABIEncoderV2 to return array of strings.

pragma solidity ^0.5.2;
pragma experimental ABIEncoderV2;

contract Test {

    string[] array;

    function push(string calldata _text) external {
        array.push(_text);
    }

    function get() external view returns(string[] memory) {
        return array;
    }
}

Upvotes: 6

Related Questions