【2022 元宇宙基础NFT之Solidity OOP编程第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];
    }
}

案例二

在下面的示例中,MappingExample合约定义了一个公共balances 映射,键类型为一个 address,值类型为 uint,将以太坊地址映射到无符号整数值。作为uint一种值类型,getter 返回一个与该类型匹配的值,您可以在MappingUser 返回指定地址处的值的合约中看到这一点。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "hardhat/console.sol";

contract MappingExample {
    mapping(address => uint) public balances;

    function update(uint newBalance) public {
        console.log(msg.sender); // msg.sender,合约地址
        console.log(newBalance);
        balances[msg.sender] = newBalance; 
    }
}

contract MappingUser {
    function f() public  returns (uint) {
        MappingExample m = new MappingExample();
        m.update(100);
        console.log(m.balances(msg.sender));
        console.log(msg.sender);
        console.log(address(this));
        console.log(m.balances(address(this)));
        return m.balances(address(this));
    }
}

结构体和字典综合案例

温馨提示:此处内容已隐藏,您必须消耗1个积分后才能查看。

或者

关注微信公众号: 程序咖元宇宙实验室
回复:程序咖巴士 ,获取验证码。
验证码:
已有 0 用户参与0
0 : 0
+1已打分
电子邮箱
  • 程序咖巴士
联系我们
  • 扫一扫,联系我们