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

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

我定义了一个映射类型的状态变量,例如映射(uint256 => uint256[])。我想把它设为 public 以便我可以从合同外访问它。但是,编译器报错TypeError: Wrong argument count for function call: 1 arguments given but expected 2.。看起来映射的自动 getter 不是 return 数组。

例如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
    }
}

不过,我可以在 returns 数组的 ContractB 中创建一个函数。

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

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