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?

Henrique Barcelos
  • 2,481
  • 4
  • 20
  • 38

1 Answers1

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...
}
dbryson
  • 6,403
  • 2
  • 27
  • 37
  • 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?" – Henrique Barcelos Mar 31 '16 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 '16 at 13:40
  • Yeah, I understand the concept of guard, but I was wondering if there is a better approach :) – Henrique Barcelos Mar 31 '16 at 13:41