iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
Blockchain

Smart Contract 開發 - 使用 Solidity系列 第 16

開發智能合約 - mapping 型別 (Day16)

你可以把 mapping 型別看做類似是一個 hash tables,它會虛擬初始化每一個 key 的值都預設為 0。但實際上 mapping 型別,並不是存 key 和 value 的真正的內容,而是 key 的 和 value 的 keccak256 hash。

因此 mapping 型別的 key 跟 value 在設定時,沒有長度的概念,並且 mapping 型別只允許使用在狀態變數。

宣告 mapping

mapping 是一個動態大小的陣列,_KeyType 除了 enumstruct 型別不能使用之外,其他的型別都支援。_ValueType 支援所有的型別,包含 mapping 型別。

語法

mapping(_KeyType => _ValueType)

範例

mapping(address => uint) public balances;

mapping 型別裡面包含 mapping 型別

mapping(uint => mapping(uint => s)) data;

設定 mapping 值

balances[msg.sender] = 100;

取得 mapping 值

uint balance = balances[msg.sender]

msg.sender 是 address 型別

mapping 型別不支援 iterable,但可以自己實作它。

pragma solidity ^0.4.0;

contract MappingExample {

  address[] funderIndexs;
  mapping (address => Funder) public funders;

  struct Funder {
    address addr;
    uint amount;
    uint createdAt;
    string name;
  }

  function add(uint _amount, string _name) public {
    funderIndexs.push(msg.sender);
    funders[msg.sender] = Funder(msg.sender, _amount, now, _name);
  }

  function iterable() public {
    for (uint i = 0; i < funderIndexs.length; i++) {
      Funder storage funder = funders[funderIndexs[i]];
      // ...  
    }
  }
}

完整範例

pragma solidity ^0.4.0;

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

    function update(uint newBalance) public {
        balances[msg.sender] = newBalance;
    }
}

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

上一篇
開發智能合約 - 函式與修飾標記 (Day15)
下一篇
開發智能合約 - 可見度和自動生成 getter 函示 (Day17)
系列文
Smart Contract 開發 - 使用 Solidity31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言