Mapping 不用太多的解釋,我們可以想像它是 宣告 Key ⇒ Vaule 的動態 Array
寫法:
mapping( _Key ⇒ _Vaule);
_Value 的部分可以定義想要的變數
以下為程式碼解說:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract MappingExample {
// 範例一
mapping(address => uint256) account; // 宣告,key = address value = int
function get(address _address) public view returns (uint256) {
return account[_address]; // 取得帳號地址資訊
}
function set(address _address, uint256 _balance) public {
account[_address] = _balance; // 資訊裡面放餘額
}
function remove(address _address) public {
delete account[_address]; // 刪除指定資訊
}
// 範例二
mapping(address => User) public Users;
struct User {
string name;
uint createdAt;
uint balance;
}
// 特別解說
// block.timestamp 區塊目前的時間
// msg.sender.balance 發送指令的人的錢包餘額
function setUser(string memory _name) public {
Users[msg.sender] = User(_name, block.timestamp, msg.sender.balance);
}
function getUser(address currect) public view returns (string memory, uint) {
User storage _user = Users[currect];
return (_user.name, _user.balance);
}
}
通常我們使用到 Mapping 就是要放多筆資料,因為可以靈活的制定key索引,讓程式快速找到自己相對應的資料,往往這樣可以省掉很多的效能(當然如果我們中間利用for 去資料也是會消耗一定的gas,所以我們可以利用此方法快速搜尋)
附上執行結果:
有任何問題可反饋: [email protected]