Solidity 学习笔记
通过学习Solidity
,然后输出文章检验自己的学习成果Github仓库
欢迎大家关注我的X
mapping(KeyType KeyName? => ValueType ValueName?) VariableName
,也可以写成mapping(KeyType => ValueType)
Key Value
的语法是Var[Key] = Value
,其中Var
是映射变量名,Key
和Value
对应新增的键值对Key Value
的语法是delete Var[Key]
,其中Var
是映射变量名,Key
是要删除的键哈希表
KeyType
可以是Solidity的值类型,bytes
,string
和合约类型
,不可以使用自定义结构体
ValueType
可以是任何类型
包含映射(Mapping)
或者数组
或者结构体
public
,那么Solidity
会自动给你创建一个getter
函数,可以通过Key
来查询对应的Value
一个类型的默认值
keccak256
的哈希值,从而便于查询实际的值length
的信息该例子是使用映射(Mapping)的例子
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Mapping {
mapping(address => uint) public map;
mapping(ValueContract => uint) public contractMap;
function getMap(address _addr) public view returns (uint){
return map[_addr];
}
function setMap(address _addr, uint _i) public {
map[_addr] = _i;
}
function removeMap(address _addr) public {
delete map[_addr];
}
function getContractMap(ValueContract _addr) public view returns (uint){
return contractMap[_addr];
}
function setContractMap(ValueContract _addr, uint _i) public {
contractMap[_addr] = _i;
}
function removeContractMap(ValueContract _addr) public {
delete contractMap[_addr];
}
}
contract NestedMapping {
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr, uint _i) public view returns (bool){
return nested[_addr][_i];
}
function set(address _addr, uint _i, bool _boo) public {
nested[_addr][_i] = _boo;
}
function remove(address _addr, uint _i) public {
delete nested[_addr][_i];
}
}
contract ValueContract {
uint public value;
constructor(uint _value) {
value = _value;
}
}
contract ValueContract {}
ValueContract
的空合约mapping(address => uint) public map;
mapping(ValueContract => uint) public contractMap;
map
和contractMap
,分别从 address 映射到 uint 和 ValueContract 映射到 uintmap
和contractMap
声明为public
,其实会自动生成get
函数function getMap(address _addr) public view returns (uint){
return map[_addr];
}
function getContractMap(ValueContract _addr) public view returns (uint){
return contractMap[_addr];
}
默认值
function setMap(address _addr, uint _i) public {
map[_addr] = _i;
}
function getContractMap(ValueContract _addr) public view returns (uint){
return contractMap[_addr];
}
function removeMap(address _addr) public {
delete map[_addr];
}
function removeContractMap(ValueContract _addr) public {
delete contractMap[_addr];
}
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr, uint _i) public view returns (bool){
return nested[_addr][_i];
}
function set(address _addr, uint _i, bool _boo) public {
nested[_addr][_i] = _boo;
}
function remove(address _addr, uint _i) public {
delete nested[_addr][_i];
}
默认值