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?


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.

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