Solidity0.8.0-数组

// SPDX-License-Identifier: GPL-3.0

//array -dynamic or fixed size
//Initialization
// Insert(push),get, update, delete,pop, length
// createing array in memoryu
//returning array from function
pragma solidity ^0.8.3;

contract Array {
    uint[] public nums = [1,2,3];   //动态数组,长度可以变化
    uint[3] public numsFixed = [4,5,6];//定长数组

    function examples() external {
        nums.push[4];//[1,2,3,4],向数组尾部推入,动态数组可以这样操作,定长数组不行
        uint x = nums[1];  //通过索引访问数组的值
        nums[2] = 777;//[1,2,777,4]//通过索引的修改数组元素
        delete nums[1];//[1,0,777,4]//通过索引删除数组元素,delete方法不能修改数组长度,所以将修改的值改成默认值,uint默认值0
        nums.pop(); //[1,0,777],弹出最后一个组数,所以数组长度会变短
        uint len = nums.length;//获取数组长度的方法

        // create array in memory
        uint[] memory a = new uint[](5);//内存中不能创建动态数组,只能根据索引修改值,pop等方法会修改数组长度,动态数组只能存在这个状态变量中
        a[1] = 123;
    }

    function returnArray() external view returns (uint[] memory){//返回,内存的索引类型
        return nums;
    }
    
    //1 函数没有定义返回值类型 (returns (uint))2 声明的局部变量没有被使用;
    //memory的类型必须在定义时就定义长度,因为内存开销要确定好,(gas limt要确定)
}

  

posted @ 2022-07-26 22:31  ZaleSwfit  阅读(102)  评论(0编辑  收藏  举报