Skip to main content

映射

映射其实就是字典,k-v 数据结构

定义方式

mapping(keyType => valueType)

映射操作: set、get、delete

  • delete 操作仅仅只是将对应的值初始化
  • get 操作获取一个不存在的 key 时,会返回初始化的数据
  • mapping 不能直接迭代,需要借助其他数据结构进行迭代
  • mapping 不能用于作为返回值
pragma solidity ^0.8.3;

contract Mapping {
mapping(address => uint256) public balances;

function setBalance(address _account, uint256 _balance) external {
balances[_account] = _balance;
}

function getBalance(address _account) external view returns(uint256) {
return balances[_account];
}

function addBalance(address _account,uint256 _amount) external {
balances[_account] += _amount;
}

function deleteBalance(address _account) external {
// 这里等价于 balances[_account] = 0;
delete balances[_account];
}
}

可迭代的 mapping

通过数组保存 Key 的值实现可遍历

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract IterableMapping {
mapping(address => uint) public balances;
mapping(address => bool) public inserted;
address[] public keys;

function set(address _key, uint _val) external {
balances[_key] = _val;
if (!inserted[_key]) {
inserted[_key] = true;
keys.push(_key);
}
}

function getSize() external view returns (uint) {
return keys.length;
}

function first() external view returns (uint) {
if (keys.length > 0) {
return balances[keys[0]];
}
return 0;
}

function last() external view returns (uint) {
if (keys.length > 0) {
return balances[keys[keys.length - 1]];
}
return 0;
}

function get(uint _i) external view returns (uint) {
if (keys.length > _i) {
return balances[keys[_i]];
}
return 0;
}
}