0

Can you explain me what this piece of code does please? i don't understand it at all.


 struct Candidate {
        uint id;
        string name;
        uint voteCount;
    }

mapping(uint => Candidate) public candidates;
uint public candidateCount;

constructor() public {
    addCandidate("candidate 1");
    addCandidate("candidate 2");
}

function addCandidate(string name) private {
    candidateCount += 1;
    candidates[candidateCount] = Candidate(candidateCount, name, 0);
}

Thank you very much

Take care

1

The constructor is a function that is called once, when you deploy a contract to the network. It cannot be called manually, after deployment. This code will run the addCandidate function twice on deployment, which adds new Candidates to the candidates array (or mapping, it's not entirely clear from the snippet you posted).

candidates[candidateCount] = ... basically assigns a value to the array, where the index is candidateCount. If the candidateCount is 0 by default, this will create a candidate for index 1 and 2.

| improve this answer | |
  • Thank you for your answer. "candidateCount" is a variable(I updated the code above). So each time a candidate is entered in the fonction the variable "candidateCount" will be increased by 1? – Pierre Aug 1 at 14:01
  • Correct, candidateCount += 1; will increment it by one, every time the addCandidate function is called. – Morten Aug 1 at 18:05
  • Thank you for your help – Pierre Aug 1 at 19:48

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