How to access Solidity mapping which has value of array type?

末鹿安然 提交于 2019-12-24 02:09:13

问题


I define a state variable of mapping type, e.g. mapping(uint256 => uint256[]). I thought to make it public so that I can access it from outside of the contract. However, the compiler reports error TypeError: Wrong argument count for function call: 1 arguments given but expected 2.. It looks like the automatic getter of the mapping doesn't return an array.

For example, ContractB is the contract to be built,

pragma solidity >=0.5.0 <0.6.0;

contract ContractB {
    mapping(uint256 => uint256[]) public data;

    function getData(uint256 index) public view returns(uint256[] memory) {
        return data[index];
    }

    function add(uint256 index, uint256 value) public {
        data[index].push(value);
    }
}

Creating a test contract to test ContractB,


import "remix_tests.sol"; // this import is automatically injected by Remix.
import "./ContractB.sol";

contract TestContractB {

    function testGetData () public {
        ContractB c = new ContractB();

        c.add(0, 1);
        c.add(0, 2);

        Assert.equal(c.data(0).length, 2, "should have 2 elements"); // There is error in this line
    }
}

I could create a function in ContractB which returns array, though.


回答1:


Unfortunately, Solidity can't return dynamic arrays yet.

But you can get elements one by one. For this, you need to pass an index to getter:

contract TestContractB {

    function testGetData () public {
        ContractB c = new ContractB();

        c.add(0, 1);
        c.add(0, 2);

        // Assert.equal(c.data(0).length, 2, "should have 2 elements"); // Don't use this
        Assert.equal(c.data(0,0), 1, "First element should be 1"); 
        Assert.equal(c.data(0,1), 2, "Second element should be 2"); 
    }
}


来源:https://stackoverflow.com/questions/57213842/how-to-access-solidity-mapping-which-has-value-of-array-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!