5

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?

Paul Razvan Berg
  • 17,902
  • 6
  • 73
  • 143

2 Answers2

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';