1. 程式人生 > >solidity智慧合約[28]-函式返回值

solidity智慧合約[28]-函式返回值

函式返回值一般形式

1
2
3
4
5
6
7
8
9
10
function  resValue() pure public returns(uint){
   uint a = 10;
   return a;
}

function  recieveValue() pure public returns(uint){
   uint b;
   b = resValue();
   return b;
}

函式命名返回值

1

2
3
4
5
6
7
8
9
10
11
12
13
//1、直接賦值、不需要return返回
function resValue2() pure public returns(uint num1){
   num1 = 100;
}
//2、如果有return,以return為準
function resValue3() pure public returns(uint num1){
 num1 = 100;
 return 99;
}
//3、不return,也不賦值,那麼為0
function resValue4() pure public returns(uint num1){
 uint b = 88;

}

函式多返回值

solidity語言支援函式的多返回值。

1
2
3
4
5
6
7
8
9
10
function mulvalue(uint a,uint b) pure public returns(uint,uint){
 uint add =  a+b;
 uint mul = a*b;
 return (add,mul);
}
//命名返回值+多返回值
function mulvalue2(uint a,uint b) pure public returns(uint add,uint mul){
  add =  a+b;

  mul = a*b;
}

案例:多返回值實現引數的反轉

狀態變數resA、resB傳遞過來之後。函式reverse2將會使得函式

1
2
3
4
5
6
7
8
9
10
function reverse(uint a,uint b) returns(uint ,uint){
   return (b,a);
}

   uint public  resA = 0;
   uint public resB = 0;

 function reverse2(uint a,uint b) {
   (resA,resB) = reverse(a,b);
}

image.png