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?

1

1 Answer 1

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]
        }
    }

}
4
  • 1
    Thanks! Wouldn't if(values[msg.sender] || usedAddresses[msg.sender]) save gas?
    – Tom Hale
    Commented Oct 16, 2017 at 5:43
  • yeah great of course :) Commented Oct 16, 2017 at 5:44
  • I'll update the answer :) Commented Oct 16, 2017 at 5:45
  • 1
    The order should actually be if ( usedAddresses[msg.sender]||values[msg.sender] ) ;) Commented Oct 16, 2017 at 5:47

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.