2

In the Ballot contract from the Solidity documentation, the Ballot function assigns

voters[chairperson].weight = 1

What does that mean? Out of the set of voters, we find the chairperson (like in a dictionary call) and assign it weight 1?

1 Answer 1

2

In the function Ballot() we see that chairperson is defined as chairperson = msg.sender;, which is the address of the account that creates the ballot.

In the next function, giveRightToVote(), we see that when the address of a person who isn't the chairperson is added to the ballot, then their weight is set to 1. i.e. They are allowed to vote on the ballot and their vote counts as "1 vote".

Therefore the line voters[chairperson].weight = 1; simply states that the person who created the ballot automatically has the right to vote (and that by default their vote counts as "1 vote").

Later on you will see that it's possible to delegate a vote to someone else, in which case a person can have a weight of more than one. (Which is why the weight is an integer value and not just a boolean "can this person vote?").

Edit:

mapping(address => Voter) public voters;

It should be pointed out that voters is a mapping that contains all possible addresses, which means we can look up the address of the chairperson or anyone else.


Edit #2:

Solidity's mapping type is effectively a hash table, but with perfect mapping, which means there are no collisions (i.e. each address maps to a distinct value). I believe this qualifies as a "minimal perfect hash function".

From the Solidity documentation:

Mappings can be seen as hashtables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. The similarity ends here, though: The key data is not actually stored in a mapping, only its sha3 hash used to look up the value.

I think the last sentence is the important one.

Virtually initialising something doesn't mean that we have a huge hash table sitting there the whole time, mostly empty, with the key data initialised for each address. What it would mean is that any address would be allowed as a key, if someone tried to do a set operation or look-up.

2
  • Good way of putting it. Although I still cant get how a mapping can contain all possible addresses...
    – TMOTTM
    Commented Jun 22, 2016 at 4:50
  • I've tried to explain it a bit better. Let me know if it's not clear :) Commented Jun 22, 2016 at 8:25

Your Answer

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

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