如何访问具有数组类型值的Solidity映射?

时间:2019-07-26 05:48:55

标签: solidity

我定义了一个映射类型的状态变量,例如映射(uint256 => uint256 [])。我考虑将其公开,以便可以从合同外部访问它。但是,编译器报告错误TypeError: Wrong argument count for function call: 1 arguments given but expected 2.。看起来映射的自动获取器不会返回数组。

例如,ContractB是要构建的合同,

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);
    }
}

创建测试合同来测试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
    }
}

我可以在ContractB中创建一个返回数组的函数。

1 个答案:

答案 0 :(得分:0)

不幸的是,Solidity还不能返回动态数组。

但是您可以一一获取元素。为此,您需要将索引传递给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"); 
    }
}