use mappings inside structs in solidity

Viewed 3503

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];
    }
}
1 Answers

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
Related