blockchain - solidity - 使用mapping ( hash )
访问量: 773
refer to:
https://ethereum.stackexchange.com/questions/65589/return-a-mapping-in-a-getall-function
声明
mapping(address => uint ) whiteList ; 用来声名, key是 address, value是 uint
使用
想要读取它的话,直接声明成 public
无法声明一个function 返回mapping.
对于某个之前不存在的key, 可以直接读取, 返回的 value值是 0
[]= 与 []
mapping['key'] 用来读取
mapping['key']= 333 用来写入
例子:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract TestMapping {
// 这里设置成 public 即可访问
mapping(address => uint) public whiteList;
function addToWhiteList(address tempAddress) external{
whiteList[tempAddress] = whiteList[tempAddress] + 1;
}
}
下面是做不到的事儿:
做不到1: 遍历一个mapping的key
暂时无法“直接”办到,所以可以声明一个state 变量, (例如 address[] keys ) 来保存每个存入mapping的key
做不到2: function return mapping
/*
这样写不行,我们无法直接return mapping
function getWhiteList() public view returns (mapping) {
return whiteList;
}
*/
做不到3: emit EventLog(mapping a )
event MyLog(mapping temp);
function addToWhiteList(address tempAddress) external{
whiteList[tempAddress] = whiteList[tempAddress] + 1;
// 这样写也不行。 无法进行 event 的emit
emit MyLog(whiteList);
}
做不到4: 直接读取一个 public state mapping,
想要读取的话,每次都需要提供一个key
