【问题标题】:How to access Solidity mapping which has value of array type?如何访问具有数组类型值的 Solidity 映射?
【发布时间】:2019-12-04 10:23:22
【问题描述】:

我定义了一个映射类型的状态变量,例如映射(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 中创建一个返回数组的函数。

【问题讨论】:

  • 嗨,看起来像一个错误,请随时报告此问题(但在检查重复之前)github.com/ethereum/solidity/issues 如果是这样,请使用问题报告的 github 链接编辑您的问题,谢谢 :)
  • 谢谢@YegorZaremba,我想将此报告给solidity,看看是否可以改进。

标签: solidity


【解决方案1】:

不幸的是,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"); 
    }
}

【讨论】:

猜你喜欢
  • 2021-04-28
  • 2014-08-13
  • 1970-01-01
  • 2014-01-20
  • 2018-12-02
  • 2019-02-26
  • 2021-08-25
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多