If I have a mapping like this

struct data {
   string name;  
   string nickname;  

mapping(address => data) public user;

How can I find out whether an address is already in the mapping or not?

if (user[_address]) 

does obviously not work.

  • You can do that by checking the value (data) or can use the arrays.
    – Aniket
    Apr 18, 2017 at 14:09

1 Answer 1


Taking advantage of the fact that all uninitialised state has zero values, you can test for existence simply by looking for a non-zero value. So to extend your test: if (user[_address].name != "") { //do something }

This requires the discipline to make sure that existing data used in existential testing does not take on valid '0' values otherwise you will return false negatives. In the worst case, you might need an existential bool

struct data {
    bool exists; // set to true 
    uint16 id; // indeces are often more useful. set to non 0
    bytes32 name;  // side note: bytes32 more efficient for this
    bytes32 nickname; // kind of struct

If you're using or come to use complex data structures, like linked lists, trees, etc, that contain node pointers/indeces, I find it good practice to dedicate index/key '0' to null - as in don't store anything at [0]. In this way, existence testing for any particular node or link is as simple as 'n != 0'

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