0xdev
0xdev

Reputation: 51

use mappings inside structs in solidity

After including a mapping inside a struct, when trying to pass the struct into a function, it has to be "storage" instead of "memory". (the "checkBalance" function is just an example here)

  1. Is it a good practice to store mapping inside struct?
  2. Any alternatives to the mapping type inside the struct? Thought of using array but it has to do the iteration to find the item.
library MappingLib {
    struct Balance {
        uint256 value;
        mapping(string => uint256) positions;
    }
    
    function checkBalance(Balance storage balance, string memory key) public returns (uint256) {
        return balance.positions[key];
    }
}

Upvotes: 3

Views: 4806

Answers (2)

Shahroz Khan
Shahroz Khan

Reputation: 1

  1. You could put the mapping outside the struct

      `mapping(string => uint256) positions;`
    

Pass in the string and get the value or you could just create the key in the mapping

    `mapping(uint256 => Balance) positions;`

Upvotes: 0

paradisensei
paradisensei

Reputation: 116

First of all mappings and any other data structures that need to be persisted in-between contract calls are always stored in storage, whether they are part of any struct or not. Now answering your questions:

  1. Yes, it's perfectly fine to have mappings inside structs
  2. In your particular case mapping seems to be the most natural option as you want to access values by keys

Upvotes: 4

Related Questions