4

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

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.

3
  • What if you get the following error? TypeError: Member "balances" is not available in struct FancyStruct. Speaker memory outside of storage. Oct 12 '20 at 21:09
  • Not sure. You may want to open a question about that, and read about Memory vs Storage. Oct 12 '20 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 '20 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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