【Solidity智能合约开发第21篇】3分钟了解Solidity 字典/映射(Mappings)

语法

mapping(_KeyType => _ValueType)

字典/映射其实就是一个一对一键值存储关系。

举个例子:

{age: 28, height: 172, name: liyuechun, wx: liyc1215}

这就是一个映射,满足_KeyType => _ValueType之间的映射关系,age对应一个28的值,height对应160name对应liyuechun, wx对应liyc1215

PS:同一个映射中,可以有多个相同的,但是必须具备唯一性。

案例

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;

contract MappingExample {

    // 测试账号

    // 0xca35b7d915458ef540ade6068dfe2f44e8fa733c

    // 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c

    // 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db

    mapping(address => uint)  balances;

    function update(address a,uint newBalance) public {
        balances[a] = newBalance;
    }

    // {0xca35b7d915458ef540ade6068dfe2f44e8fa733c: 100,0x14723a09acff6d2a60dcdf7aa4aff308fddc160c: 200,0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db: 300 }

    function searchBalance(address a) view public returns (uint) {

        return balances[a];
    }
}

结构体和字典综合案例

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;

contract CrowdFunding {

    // 构建一个出资人结构体
    struct Funder {
        address addr;  // 出资人钱包地址
        uint amount;   // 出资数量
    }

    // 构建一个运动员结构体
    struct Campaign {
        address payable beneficiary; // 收款地址
        uint fundingGoal; // 众筹目标
        uint numFunders; // 出资人数量
        uint amount; //当前收到款项额度
        mapping (uint => Funder) funders; // 出资人信息
    }

    uint numCampaigns; // 计数器
    mapping (uint => Campaign) campaigns; // 存储需要众筹的运动员

    // 创建运动云结构体对象
    function newCampaign(address payable beneficiary, uint goal) public returns (uint campaignID) {
        campaignID = numCampaigns++; 
        campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0);
    }

    // 给某一个运动员直接转账
    function contribute(uint campaignID) public payable {
        Campaign storage c = campaigns[campaignID]; // 根据campaignID读取对象
        c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value}); // 存储出资人信息
        c.amount += msg.value; // 更新收到款项的总额度
    }

    // 检查某个运动员众筹额度是否达标
    function checkGoalReached(uint campaignID) public returns (bool reached) {
        Campaign storage c = campaigns[campaignID];
        if (c.amount < c.fundingGoal)
            return false; // 不达标,返回false
        // 达标以后,将钱从合约地址提到运动员自己的钱包
        uint amount = c.amount;
        c.amount = 0;
        c.beneficiary.transfer(amount);
        return true;
    }
}

该内容来自于互联网公开内容,非区块链原创内容,如若转载,请注明出处:https://htzkw.com/archives/24989

联系我们

aliyinhang@gmail.com