'Solidity mapping not returns an array in a struct
The Solidity's mapping not returns an array inside a struct (when call mapping_data()
, the data variable is undefined).
Just be able to read it from read()
function.
Does anyone know a reason?
struct structPackage
{
uint256 ui;
string[2] data;
}
// the mapping_data(address) is not includes data variable, undefined.
mapping(address => structPackage) public mapping_data;
constructor()
{
structPackage storage data_package = mapping_data[msg.sender];
data_package.data[0] = "test1";
data_package.data[1] = "test2";
}
// This function shows data as expected, [ 'test1', 'test2' ].
function read() external view
returns (structPackage memory)
{
structPackage storage data_package = mapping_data[msg.sender];
return data_package;
}
Tested on Remix, mapping_data doesn't return the array inside struct
Solution 1:[1]
When a struct
is used as value inside a mapping
, the getter function of the mapping
will ignore the mappings
or arrays
used inside the struct
, because there is no easy way to provide keys or indexes to get the specific element from array or mapping. This mechanism exists to avoid high gas costs when returning an entire array or entire mapping.
Hence, if you want to access a complete array or mapping inside a struct (which is used as a value in a mapping which is public) make separate specific getters as required(Similar to as you wrote your read
method).
Read Getter Functions docs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | adzo261 |