solidity中的mapping

mapping可以理解为python中对字典的键值遍历,键是唯一的而值是可以重复的

mapping函数的构造: mapping(_KeyType => _ValueType)

 mapping (address => uint) public balances;

上文代码解析:mapping(键类型=>值类型), 在上述代码中,映射的名字是balances,权限类型为public,键的类型是地址address,值的类型是整型uint

 

 contract MappingExample{
     mapping(address => uint) public balances;
     
     function update(uint amount) returns (address addr){
         balances[msg.sender] = amount;
         return msg.sender;
    }
 }

在上述代码中,首先定义了一个balance的映射. msg.sender为创建合约用户的地址,将用户地址放入balance中(也就是代码balances[msg.sender])以定位到账户地址的balance

 

另一个例子:

 pragma solidity ^0.5.0;
 
 contract LedgerBalance {
    mapping(address => uint) public balances;
 
    function updateBalance(uint newBalance) public {
       balances[msg.sender] = newBalance;
    }
 }
 contract Updater {
    function updateBalance() public returns (uint) {
       LedgerBalance ledgerBalance = new LedgerBalance();
       ledgerBalance.updateBalance(10);
       return ledgerBalance.balances(address(this));
    }
 }

 

OutPut:

 {
    "0": "uint256: 10"
 }
 
posted @ 2022-05-03 14:33  YanAemons  阅读(430)  评论(0编辑  收藏  举报