Solidity Storage Variables – How to Check If a Storage Variable is Empty

contract-developmentsolidity

How do I check whether a storage variable is "empty", i.e., no value has been assigned to it, or the value has been deleted?

For a string, I'd convert it to bytes and check for length 0. And for uints, I'd check whether it equals 0.

But what about structs (or other types that I haven't mentioned) ?

Best Answer

All storage items have a default value equivalent to zero that is identical whether something is stored as that value or the value does not exist.

With a struct, it is as if the struct already exists, but with all its members set to their defaults. There is no pure way to ask "does this struct exist?".

You can can handle this by giving your struct a field called something like .exists, and setting it to true when you create the struct. However, in practice you normally find that there is some field in your struct that always happens to be non-zero if the struct exists, so you can check for that instead of creating a dedicated field for that purpose.

Related Topic