solidity数组的使用

长度固定的数组

  • uint[]定义的数组,可以使用引用查看索引位置的数值,使用.length得到数组的长度
  • byte定义的数组,将字符串以十六进制形式保存,不能使用.lengthbyte默认值为0
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract FixedSizeArrays{
    uint[3] public numbers = [2, 3, 4];
    
    bytes1 public b1;
    bytes2 public b2;
    bytes3 public b3;
    
    function setElement(uint index,uint value) public{
        numbers[index] = value;
        // b3[index] = value;
    }
    
    function getLength() public view returns(uint){
        return numbers.length;
        // return bytes3.length;
    }
    
    function setBytesArraty() public{
        b1='a';
        b2='ab';
        b3='z';
    }
}
  • 默认值
  • 执行setBytesArray()函数

动态数组

  • 可以使用push 和 pop 函数
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract DynamicArrays{
    uint[] public numbers;
    
    function getLength() public view returns(uint){
        return numbers.length;
    }
    
    function addElement(uint item) public{
        numbers.push(item);
    }
    
    function getElement(uint i) public view returns(uint){
        if(i < numbers.length){
            return numbers[i];
        }
        return 0;
    }
}

string 和 bytes

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract BytesAndString{
    bytes public b = 'abc';
    string public s;
    
    function getElement() public view returns(bytes1){
        return b[0];
        
        // return s[0];
    }
    
    function getLength() public view returns(uint){
        return b.length;
        // return s.length;
    }
}
posted @ 2022-11-05 20:46  伶俐虫虫  阅读(254)  评论(0)    收藏  举报