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

古城微笑少年丶 2022-06-02 05:37 382阅读 0赞

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类型

  1. mapping (bytes32 => uint) public balances;

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

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

Step1-4 完整代码如下:

  1. pragma solidity 0.4.10;
  2. contract demo{
  3. mapping (bytes32 => uint) public balances;
  4. function demo() {
  5. balances["steve"] = 100;
  6. balances["nathan"] = 1000;
  7. }
  8. function add(bytes32 usr,uint amount) {
  9. balances[usr] += amount;
  10. }
  11. function update(bytes32 usr, uint amount) {
  12. balances[usr] = amount;
  13. }
  14. function del(bytes32 usr) {
  15. balances[usr] = 0;
  16. }
  17. }

执行Add的结果如图所示:

import_mapping_01.png

执行Update的结果如图所示:

import_mapping_04.png

#

执行Delete的结果如图所示:

import_mapping_03.png


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

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

stevenkcolin.jpg

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

ethchinese.jpg

发表评论

表情:
评论列表 (有 0 条评论,382人围观)

还没有评论,来说两句吧...

相关阅读