2

I'm trying to use a mapping inside a struct:

struct PoolStruct {
    uint currentUserID;
    uint activeUserID;
    uint price;
    uint minimalReferrals;
    mapping(uint => address) poolUserList;
  }

the code compiles, so i guess it's somehow permitted. The problem starts when i try to assign to that property:

PoolStruct memory pool;

pool = PoolStruct({
  currentUserID: 1,
  activeUserID: 1,
  price: POOL_PRICES[i],
  minimalReferrals: POOL_MINIMAL_REFERRALS[i]
});

pool.poolUserList[1] = msg.sender;

get an error on the last line...

TypeError: Member "poolUserList" is not available in struct Definitions.PoolStruct memory outside of storage.
       pool.poolUserList[currUserID] = msg.sender;
       ^---------------^

Is there any way to make this work?

8
  • 1
    What error are you getting? What is currUserID? Jul 1 '20 at 13:17
  • @goodvibration, i edited the question with the error. currUserID is a uint (1) Jul 1 '20 at 13:24
  • Yeah, well, you can use mapping only in storage (i.e., non-local) variables. So the same goes for a struct which holds a mapping. Jul 1 '20 at 13:29
  • You probably wanna take that mapping outside the PoolStruct structure, and redefine it as mapping(uint => PoolStruct) poolUserList. Jul 1 '20 at 13:30
  • could you give me an example? Jul 1 '20 at 13:30
5

The problem is that mappings can only live in storage. When you define PoolStruct memory pool;, the mapping member cannot be created in memory, and therefore the memory struct should be treated as if the mapping member never existed (for solidity < 0.7.0).

Starting from solidity 0.7.0, the line PoolStruct memory pool will produce an error saying that structs containing (nested) mappings must have storage as data location.

4
  • @hrkshnn, Then, how should I declare? 'PoolStruct storage pool' also seems to throw an error. Saying 'Struct containing a (nested) mapping cannot be constructed.' Sep 14 '20 at 16:14
  • @Sang-hoon-Shin what does the error say?
    – hrkrshnn
    Sep 14 '20 at 16:16
  • It says "Struct containing a (nested) mapping cannot be constructed" Sep 14 '20 at 16:23
  • Please check my question: ethereum.stackexchange.com/questions/87451/… Sep 14 '20 at 16:24
0

Just keep the mapping outside the struct. you do not have to keep inside the struct

     mapping(uint => address) poolUserList;

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.