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

猜你喜欢

转载自blog.51cto.com/13784902/2321576