Solidity存储和计数次数颜色被投票支持

问题描述

所以我只是在学习坚固性,我想计算选择一种颜色的次数。现在我知道我可以做到:

uint public red = 0;

function VoteRed() public 
 { 
 red++;
 }

但是我必须事先用每种颜色编码

要做的是让用户使用字符串为颜色“投票”。

如果选择了颜色,则只需在颜色上加上+1。

如果尚未选择颜色,则其会添加颜色名称,然后添加+1。

所以可以说我想投票“黄色”。我将字符串“ Yellow”发送到合同,它存储数据“ Yellow”以及为其投票的次数(1)。

如果其他人对“黄色”投了票,它只会在“黄色”数据中添加+1(2)

依此类推...

所以我想可能是这样的:

function VoteColor(string memory color) public 
 { 
 // how to store the data and count
 }

但是我不确定如何存储颜色以及该颜色的计数器。

解决方法

考虑使用简单的映射:mapping(string => uint256)。 请记住,任何String都是使用0初始化的。

这是一个简化的示例:

pragma solidity >=0.4.22 <0.7.0;

contract Bla {

    mapping(string => uint256) colors;
    
    function voteColor(string memory color) public { 
        colors[color]++;
    }
    
    function getColorCount(string memory color) public view returns (uint256) {
        return colors[color];
    }
}