Solidity中函数返回值,静态动态数组

新建函数,并确定返回值
 function New1() public pure returns(uint,bool){
        return (98,true);
    }
    function New2() public pure returns (uint x,bool b){
        return(5,false);
    }
    function New3() public pure returns (uint x,bool b){  
        x=64;
        b=true;
    }

常规写法如上,如果想通过一个函数返回值给另一个函数

//承接函数的多种写法
    function New4() public pure  returns (uint x, bool b){
        ( x, b) = New1();
        //只返回一个数据
        //(uint x,) = New1(); 
        //(, bool b) = New1();   
    }
    function New4() public pure  returns (uint , bool){
        (uint x,bool b) = New1();
        return (x,b);  
    }
    function New4() public pure  returns (uint , bool){
        (,bool b) = New1();
        (uint x,) = New1();
        return (x,b);  
    }

如上如果想通过一个函数给另一个函数提供返回值则可以采取三种方法,但是要注意返回值的数据类型,两个函数要保持一致。

 

对于静动态数组。

uint[] public nums1 = [1,2,3]; //动态数组,长度可变
uint[3] public nums2 = [4,5,6];//定长数组,长度不可变,且必须初始化所有元素

其中有些特殊的写法,包括增删。

function New1() public {
        nums1.push(4); //向数组尾部添加数据
        x = nums1[1];  //赋值
        delete nums1[1]; //删除原先数据,并填充为0 
        nums1.pop();  //将数组的最后一位弹出
        k = nums1.length; //得出数组长度

    } 

对于数组的赋值,不同与其他语言的直接根据索引或者地址来对应赋值,Solidity中的数组赋值首先要确定数组长度,对于静态数组没什么好说的,长度一定不可修改,直接循环赋值就行。对于动态数组,首先确定接收数组的长度,例如先创建一个跟数组new1相同类型的动态数组new3,然后

 nums3 = new uint[](nums1.length);

如果想临时创建数组来赋值

uint[] memory result = new uint[](nums1.length);

用来确定长度,之后用“for”循环

for (uint i = 0; i < nums1.length; i++) {
            nums3[i] = nums1[i];
        }
或
 for (uint i = 0; i < nums1.length; i++) {
            result[i] = nums1[i];
        }

将动态数组new1中的元素赋值给数组new3和result

posted @ 2024-07-20 11:08  昏睡的云雪  阅读(20)  评论(0编辑  收藏  举报