1

This is a variation on this question.

I have a mapping between an address and a struct like this...

struct myStruct{
    string name,
    uint height
}

mapping (address=>myStruct) myMapping

if I access myMapping with an address key that hasn't been seen before, what gets returned?

e.g.

x = myMapping[unknownaddress];

What is in x?

I get a compile error if I compare to zero like this...

if (myMapping[unknownaddress] == 0){
   ...
}

Operator != not compatible with types struct MyStruct and int_const 0

Should I expect and "empty" or zeroed struct?

e.g.

x = myMapping[unknownaddress];
x.name = ""
x.height = 0

2 Answers 2

1

First of all, x = myMapping["unknownKey"]; will return error as key for your map is address, not string.

By giving a random address:

myStruct public x = myMapping[0x5c6B0f7Bf3E7ce046039Bd8FABdfD3f9F5021678];

x represents an un-initialized struct. Every field of this struct will be set to the default value. In this case, your name field will be empty and height will be 0. It would have been initialized to false if you had bool field. And finally, if you had address field, it would have been 0x0000000000000000000000000000000000000000

Here complete code:

struct myStruct{
    string name;
    uint height;
    bool test;
    address tryy;
}

mapping (address=>myStruct) public myMapping;

myStruct public x = myMapping[0x5c6B0f7Bf3E7ce046039Bd8FABdfD3f9F5021678];

By deploying on Remix, you can retrieve the value for x and its fields.

1
  • oops, great catch, I will adjust my question to get rid of the string key
    – Simon
    Mar 27, 2022 at 14:53
0

All unwritten storage in the EVM state is zeroed out. Thus, reading any uninitialized storage variable is zeroes, including the struct members.

See also this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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