Luke
Luke

Reputation: 155

How can I access the variables of a struct that is assigned to a mapping?

I want to change the variables of instances of structs that have been created. I have a Candidate struct assigned to an address variable in a mapping, and the address of the voter assigned to the address of the candidate they voted for.

struct Candidate {
        address candidateAddress;
        string candidateName;
        int numVotes;
    }

mapping(address => address) votes;
mapping(address => Candidate) candidates;

I have tried the following

function castVote(address _address) public {
        votes[msg.sender] = _address;
        candidates[_address].numVotes += 1;
    }

This does not throw an error, but when I test numVotes stays at 0 for the two test candidates I have hard-coded like so.

Candidate public candidateOne = Candidate(0x5B38Da6a701c568545dCfcB03FcB875f56beddC4, "Adam Apple", 0);
    Candidate public candidateTwo = Candidate(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2, "John Doe", 0);
    
    
    function assignCand() public {
        candidates[0x5B38Da6a701c568545dCfcB03FcB875f56beddC4] = candidateOne;
        candidates[0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2] = candidateTwo;
    }

I'm still a Solidity beginner so any help would be greatly appreciated :) Thank you!

Upvotes: 0

Views: 804

Answers (1)

Whytecrowe
Whytecrowe

Reputation: 31

One way to do this:

function castVote(address _address) public {
            votes[msg.sender] = _address;
            Candidate storage candi = candidates[_address];
            candi.numVotes = candi.numVotes + 1; // think about using SafeMath here unless it doesn't seem to ever overflow
        }

Another way:

function castVote(address _address) public {
            votes[msg.sender] = _address;
            Candidate memory candi = candidates[_address];
            candi.numVotes = candi.numVotes + 1;
            candidates[_address] = candi;
        }

Try both and compare gas usage. I do not remember exactly, but one will be cheaper.

Upvotes: 1

Related Questions