0

我想更改已创建的结构实例的变量。我有一个Candidate分配给address映射中变量的结构,并将选民的地址分配给他们投票的候选人的地址。

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

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

我试过以下

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

这不会引发错误,但是当我numVotes对两个测试候选人的测试保持在 0 时,我已经像这样进行了硬编码。

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;
    }

我仍然是 Solidity 初学者,因此我们将不胜感激 :) 谢谢!

4

1 回答 1

1

一种方法:

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
        }

另一种方式:

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

尝试两者并比较气体使用情况。我不记得确切,但一个会更便宜。

于 2021-11-05T00:46:22.807 回答