一 . mapping
映射(mapping)在声明时的形式为 mapping(KeyType => ValueType)
,可以根据KeyType 得到ValueType
数组类型(除bytes和 string)不可以作为 KeyType,其它类型均可以作为KeyType
ValueType可以是包括映射类型在内的任何类型
contract mapTest1 {
mapping(address => uint) myMap;
function get(address _addr)public view returns(uint){
return myMap[_addr];
}
function set(address _addr,uint _value) public {
myMap[_addr] = _value;
}
function remove(address _addr) public{
delete myMap[_addr]; //delete将myMap[_addr]的值变成uint类型默认值
}
}
contract mapTest2 {
mapping(address=> mapping(uint=>bool)) myMap; //嵌套mapping
function get(address _addr,uint i) public view returns(bool){
return myMap[_addr][i];
}
function set(address _addr,uint i,bool b) public {
myMap[_addr][i] = b;
}
}
二. array
数组支持动态长度数组和固定长度数组
contract ArrayTest1 {
uint[] a; //动态长度数组
function push(uint _value) public{
a.push(_value); //数组长度 +1
}
function pop() public{
a.pop(); //数组长度 -1
}
function length() public view returns(uint){
return a.length;
}
function remove(uint _index) public {
delete a[_index]; //delete 不改变数组长度,只是将值设为对应类型的初始值
}
}
contract ArrayTest2 {
uint[10] a; //固定长度数组
function push(uint _value) public{
// a.push(_value); //不支持
}
function pop() public{
// a.pop(); //不支持
}
function length() public view returns(uint){
return a.length;
}
function remove(uint _index) public {
delete a[_index]; //delete 不改变数组长度,只是将值设为对应类型的初始值
}
}
contract ArrayTest3{
uint[] a = new uint[](10); //通过new 创建长度为10的动态数组
function setA() public{
a[0] =1;
a[1]=2;
a.push(4); //数组长度 +1,a[10] =4
}
function lengthB() public pure returns(uint){
uint[] memory c = new uint[](2); //通过new 创建长度为2的固定长度数组
c[0] =1;
c[2] =2;
// c.push(3); //不支持,对于memory的变长数组,不支持push修改length属性,其效果等同于固定长度数组。
return c.length;
}
}
三. struct
struct可以在contract外声明, 在另外一个contract 中import
pragma solidity ^0.8.3;
struct B{
string name;
uint age;
}
contract StructTest {
struct A{
string name;
uint age;
}
A a;
function set(string memory name,uint age) public {
a = A(name,age);
}
function getName() public view returns(string memory){
return a.name;
}
}
----------------------------------------------------------------
pragma solidity ^0.8.3;
import "./StructTest.sol";
contract StructTest {
B b;
}