8

I have the following statements:

Voter sender = voters[msg.sender];
if (!sender || sender.voted) throw;

I'm new to solidity, so I might not be aware of how (or if) coercion works.

As I found out in this question,

[...] every possible key exists and is mapped to a value whose byte-representation is all zeros [...]

Knowing that, shouldn't the !sender statement above return true?

1 Answer 1

14

If Voter is a struct, the code !voter[sender] will probably result in an error. In your case, you'll want to check the voted or another field in the Voter struct.

For now, checking guards via voters[msg.sender].voted == 0 is probably the most reliable approach.

As a side note, strings can be a bit tricker: some_string == 0 will not work. In this case I use:

function(string value) { 
   if (bytes(value).length == 0)
     ...don't do it...
}
3
  • This is the exact same question I linked in my question. The accepted answer states "you check that a value is defined in the mapping by checking it is not zero.". So, my question can be rephrased as: "How can I check if a struct is not zero?" Mar 31, 2016 at 13:38
  • How about voters[msg.sender].voter != 0? The main thing is you must check a field in the struct. Not the struct itself
    – dbryson
    Mar 31, 2016 at 13:40
  • Yeah, I understand the concept of guard, but I was wondering if there is a better approach :) Mar 31, 2016 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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