An example of a a mapping

mapping (address => address) yourNewMapping;

Is there a way to have

yourNewMapping[msg.sender] = defaultValue

Say upon default through a constructor, for all users.


No, it’s not possible to define a default value in that way.

A mapping(KeyType => ValueType) always maps a key onto a 256-bit/32-byte storage slot; if that storage slot is blank (e.g. it was never written to), it will contain 0x0000000000000000000000000000000000000000000000000000000000000000. How these zero bytes are interpreted as a value depends on the mapping’s value-type. E.g. for a mapping(? => bool), this 0-value will be parsed as false. For a mapping with value-type address, the 0-value will be parsed as 0x0000000000000000000000000000000000000000, or address(0).

So the default value for mapping(address => address) will be address(0).

Assuming you will never be using 0 as an actual valid value, if you want to have a default value that is not 0, what you can do is to translate the 0-value to your desired default value every time you read the mapping, e.g.:

address value = yourNewMapping[msg.sender];
value = value == address(0) ? yourDefaultValue : value;
  • 1
    Just to clearify; default value of mapping is the default value of the second argument of map. So it's 0 for something mapped to a x-> uint; 0x0000000000000000000000000000000000000000 for x-> address and so on May 12 '21 at 17:22
  • @PrashantPrabhakarSingh I inserted a paragraph to elaborate on your clarification. Thanks.
    – dwardu
    May 12 '21 at 21:25

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.