Mappings are normally declared in the top part of the contract, however is there any way to instantiate a mapping - which belongs to a struct - while in a function?
Asked
Active
Viewed 3,335 times
2 Answers
2
This is how I managed to do it:
pragma solidity ^0.4.24;
contract FancyContract {
struct FancyStruct {
address from;
address to;
mapping (address => uint256) balances;
}
FancyStruct public fancyStruct;
function fancyFunction()
public
{
fancyStruct = FancyStruct({
from: address(0x01),
to: address(0x02)
});
fancyStruct.balances[address(0x01)] = 10;
fancyStruct.balances[address(0x02)] = 20;
}
}
You use the braces-based method to initialise the struct, omit the mapping in the declaration and then interact with the mapping inside as you would normally do with a storage variable.
Paul Razvan Berg
- 17,902
- 6
- 73
- 143
0
The correct way to initialise a struct that includes a mapping is by setting its fields one by one:
struct Book {
string title;
string desc;
mapping(uint => Rating);
}
item[_id].title = 'example';
item[_id].desc = 'example';
codingexplorer
- 11
- 2
TypeError: Member "balances" is not available in struct FancyStruct. Speaker memory outside of storage.
– NYC Tech Engineer Oct 12 '20 at 21:09