Solidity Structs – What is the Zero, Empty, or Null Value?

contract-developmentsoliditystruct

If I have a mapping of string => custom defined struct, how do I check if a value is defined in the mapping?

The docs state that "every possible key exists and is mapped to a value whose byte-representation is all zeros".

What is the zero-value of a custom defined struct such that one can conditionally check for its existence?

Best Answer

You check that a value is defined in the mapping by checking it is not zero.

If an explicit setting of zero has meaning for your application, you need auxiliary data (or structure) to track when a value of zero has been explicitly set.

A lightweight approach would be to add a bool property to the struct (say named initialized), and to set it to true when the zero is explicitly set. As all bools are false (0) by default, you can check against the value true.

Alternatively, check that each member of the struct is zero. If a member is a string, cast it to bytes and then check its length is zero.

For an example see How to test if a struct state variable is set

Another data structure or mapping may be needed depending on the application.


Here is a related example on using a pair to check the meaning of zero:

contract C {
    uint[] counters;
    function getCounter(uint index)
        returns (uint counter, bool error) {
            if (index >= counters.length) return (0, true);
            else return (counters[index], false);
        }
    function checkCounter(uint index) {
        var (counter, error) = getCounter(index);
        if (error) { ... }
        else { ... }
    }
}
Related Topic