区块链学堂(27):Mapping 类型

Mapping types are declared as mapping(_KeyType => _ValueType). Here _KeyType can be almost any type except for a mapping, a dynamically sized array, a contract, an enum and a struct. _ValueType can actually be any type, including mappings. here

简单地说mapping就是一种hashtable, 由一个key对应一个value

最简单的mapping类型

mapping (bytes32 => uint) public balances;

我们可以撰写一个Mapping类型的demo合约

Step 1: 首先是定义一个mapping(bytes32=>uint) public balances
pragma solidity 0.4.10;
contract demo{
    mapping (bytes32 => uint) public balances;
}
Step 2: 添加一个构造函数
pragma solidity 0.4.10;
contract demo{
    mapping (bytes32 => uint) public balances;
    function demo() {
        balances["steve"] = 100;
        balances["nathan"] = 1000;
    }
}
Step 3: 添加一个方法 Add()
    function add(bytes32 usr,uint amount) {
        balances[usr] += amount;
    }
Step 4: 添加一个 update()
    function update(bytes32 usr, uint amount) {
        balances[usr] = amount;
    }
Step 5: 添加一个 del()
    function del(bytes32 usr) {
        balances[usr] = 0;
    }
Step1-4 完整代码如下:
pragma solidity 0.4.10;
contract demo{
    mapping (bytes32 => uint) public balances;
    function demo() {
        balances["steve"] = 100;
        balances["nathan"] = 1000;
    }

    function add(bytes32 usr,uint amount) {
        balances[usr] += amount;
    }

    function update(bytes32 usr, uint amount) {
        balances[usr] = amount;
    }

    function del(bytes32 usr) {
        balances[usr] = 0;
    }
}

执行Add的结果如图所示:

执行Update的结果如图所示:

执行Delete的结果如图所示:


原文:http://www.ethchinese.com/?p=1115

QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin

获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值