我定义了一个映射类型的状态变量,例如映射(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 中创建一个返回数组的函数。
不幸的是,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");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)