区块链学堂(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
获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网
还没有评论,来说两句吧...