0

I am trying to write a simple election contract, currently trying to add candidates to an array of Candidates in my Election struct.

Can this be done and if so how can it be implemented? The code works fine when adding a single candidate without making it an array.

struct Candidate {
        uint256 candidateID;
        uint256 voteCount;
        string name;
    }
struct Elections {
        uint256 elecID;
        Candidate[] candidates;
    }
mapping(uint256 => Candidate) public candidates;
mapping(uint256 => Elections) public elections;
 
function createElection(string[] memory _names) public {
        electionCount++;
        
        
        elections[electionCount].candidates[0] = Candidate(0, 0, _names[0]);


        elections[electionCount].candidates[1] = Candidate(1, 0, _names[1]);
        //elections[electionCount] = Election(electionCount, _candidates);
        
    }
2
  • I am not sure about your use case. But maybe nested maps would help you? For example: mapping(Elections=>mapping(uint=>Candidate) public elections. This link explains it well solidity-by-example.org/mapping
    – Sky
    Commented Feb 24, 2022 at 8:39
  • Sorry for the lateness of this reply, I am a student and was busy, only getting back to this work now. Appreciate the help, looks like nested mappings could be the correct method. Basically I need my election struct to contain my structure of candidates as each election will have separate candidates
    – GotNoClout
    Commented Mar 1, 2022 at 13:23

1 Answer 1

0

Yes, you can add an array of candidates to the elections struct.

Elections storage newElection = elections[electionCount];

newElection.candidates.push();

Candidate storage newCandidate = elections[electionCount].candidates[0];

newCandidate.candidateID = 0;
newCandidate.voteCount = 0;
newCandidate.name = "candidate name";

You can try something like this. Dynamic arrays can only be accessed in storage, not memory, which is something to keep in mind.

Also, you might want to take a look at this project: https://github.com/hjk216/CityVotingSC

Let me know if this helps.

2
  • Tried implementing thiss and still no luck, compiles in remix but the execution fails when calling the function
    – GotNoClout
    Commented Mar 3, 2022 at 3:42
  • Got it working, Thanks for the help! What you provided is correct but I jut needed to initialise the first element of my election array before hand with elections.push(); and instead used e.candidates.push(Candidate(1, 0, _name[0])); to add a candidate. NOTE: I replaced newElection with e
    – GotNoClout
    Commented Mar 3, 2022 at 3:50

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.