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?

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()
        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.

  • What if you get the following error? TypeError: Member "balances" is not available in struct FancyStruct. Speaker memory outside of storage. Oct 12, 2020 at 21:09
  • Not sure. You may want to open a question about that, and read about Memory vs Storage. Oct 12, 2020 at 21:11
  • I just realized that your fancyStruct is a state variable. I'm trying to initialize a struct within the function without using a state variable. Oct 12, 2020 at 21:17

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.