3

How can I know if a key is unset?

The Solidity documenation on Mappings says:

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.

If I'm mapping to an int, how can I differentiate between key with a value which is set to zero, vs key with an unset value which defaults to 0x0?

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
Tom Hale
  • 3,107
  • 4
  • 20
  • 37
  • If zero has meaning, then you have to explicitly set a flag. Have a look at Mapping with Struct over here: https://ethereum.stackexchange.com/questions/13167/are-there-well-solved-and-simple-storage-patterns-for-solidity/13168#13168 – Rob Hitchens Oct 16 '17 at 04:39

1 Answers1

1

If I had to do this, I would use two mappings, one for the values and one to check whether if the address is used (keeping a flag - as @RobHitchens has suggested in a comment).

pragma solidity ^0.4.0;

contract Example {

    mapping(address => uint) public values;
    mapping(address => bool) public usedAddresses;


    function update(uint newVal) {

        values[msg.sender] = newVal;
        usedAddresses[msg.sender] = true;
    }

    function dosomethiingwithval(){

        if(usedAddresses[msg.sender]){ 

             //do whatever with values[msg.sender]
        }
    }

}
Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38