Reputation: 43
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.
Upvotes: 3
Views: 4116
Reputation: 9717
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");
}
}
Upvotes: 3