solidity:2.mapping、array和struct

一 . 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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值