Mapping
contract Mapping {
// state mapping 定义
mapping(address => uint) public ethBalances;
mapping(address => mapping(address => uint)) coinBalances;
function demo() external {
//操作
ethBalances[msg.sender] = 123; // 设置,修改
ethBalances[msg.sender] += 234;
uint bal = ethBalances[msg.sender]; // 取值
uint zero = ethBalances[address(1)]; // 未设置返回默认值
delete ethBalances[msg.sender]; // 删除
}
}可循环 Map 的实现
contract LoopMapping {
//可循环 mapping 实现
mapping(address => uint) public balances;
mapping(address => bool) public exists;
address[] public keys;
function set(address _key, uint _val) external {
balances[_key] = _val;
if (!exists[_key]) {
exists[_key] = true;
address.push(_key);
}
}
function getSize() external returns (uint) {
return keys.length;
}
function getFirst() external returns (address) {
if (getSize() == 0) {
return address(0);
}
return keys[0];
}
function getLast() external returns (address) {
if (getSize() == 0) {
return address(0);
}
return keys[keys.length - 1];
}
function get(uint _index) external returns (address) {
require(_index < getSize(), "index out of bound");
return keys[_index];
}
}Last updated
Was this helpful?