0

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) ?

3

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.

  • Thanks, what is the zero value of strings? I cannot compare a storage string to ""? – Shuzheng Nov 7 '17 at 12:16
  • @Shuzheng The zero value of strings is an empty string "". You can check if a storage string str is empty like this: bytes(str).length == 0 – Jesse Busman Nov 7 '17 at 12:40
  • Yes, it should be "". – Edmund Edgar Nov 7 '17 at 12:42
  • Why isn't it possible to just do str == ""? – Shuzheng Nov 7 '17 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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