10.Mapping
Maps的创建语法:mapping(keyType => valueType)
.
- The keyType can be any built-in value type, bytes, string, or any contract.
- valueType can be any type including another mapping or an array.
Mappings are not iterable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Mapping {
//mapping
mapping(address => uint256) public balances;
mapping(address => mapping(address => bool)) public isFriend;
function examples() external {
// set
balances[msg.sender] = 123;
// get
uint256 bal = balances[msg.sender];
uint256 bal2 = balances[address(1)];
// update
balances[msg.sender] += 456; //123+345
// delete
delete balances[msg.sender]; //0
isFriend[msg.sender][address(this)] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
Mapping in Solidity is not iterable unless you internally store all keys that were inserted.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract IterableMapping {
//mapping
mapping(address => uint256) public balances;
mapping(address => bool) public inserted;
address[] public keys;
function set(address _key, uint256 _val) external {
balances[_key] = _val;
if (!inserted[_key]) {
inserted[_key] = true;
keys.push(_key);
}
}
function getSize() external view returns (uint256) {
return keys.length;
}
function first() external view returns (uint256) {
return balances[keys[0]];
}
function last() external view returns (uint256) {
return balances[keys[keys.length - 1]];
}
function get(uint256 _i) external view returns (uint256) {
return balances[keys[_i]];
}
}