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 namedinitialized
), and to set it totrue
when the zero is explicitly set. As all bools are false (0) by default, you can check against the valuetrue
.Alternatively, check that each member of the struct is zero. If a member is a
string
, cast it tobytes
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: