Solidity Minimalist #4. Function output

In this lecture, we will introduce the output of Solidity functions, including: returning various variables, named return, and using destructuring assignment to read all and part of the return value.

return value return and returns

Solidity has two keywords related to function output: return and returns. The difference between them is:

  • returns are added after the function name to declare the returned variable type and variable name;
  • return is used in the function body to return the specified variable.
// 返回多个变量
function returnMultiple() public pure returns(uint256, bool, uint256[3] memory){
  return(1, true, [uint256(1),2,5]);
}

In the above code, we declare that the returnMultiple() function will have multiple outputs: returns(uint256, bool, uint256[3] memory), and then we use return(1, true, [uint256(1),2,5]) in the function body to determine the return value.

named return

We can indicate the name of the returned variable in returns, so that solidity will automatically initialize these variables and automatically return the values ​​​​of these functions without adding return.

// 命名式返回
function returnNamed() public pure returns(uint256 _number, bool _bool, uint256[3] memory _array){
  _number = 2;
  _bool = false; 
  _array = [uint256(3),2,1];
}

In the above code, we use returns(uint256 _number, bool _bool, uint256[3] memory _array) to declare the return variable type and variable name. In this way, we only need to assign values ​​to the variables _number, _bool and _array in the main body and they can return automatically.

Of course, you can also use return to return variables in named returns:

// 命名式返回,依然支持return
function returnNamed2() public pure returns(uint256 _number, bool _bool, uint256[3] memory _array){
  return(1, true, [uint256(1),2,5]);
}

destructuring assignment

Solidity uses the rules of destructive assignment to support reading all or part of the return value of a function.

  • Read all return values: declare variables, and separate the variables to be assigned with , and arrange them in order.
uint256 _number;
bool _bool;
uint256[3] memory _array;
(_number, _bool, _array) = returnNamed();
  • Read part of the return value: Declare the variable corresponding to the return value to be read, and leave blank if not read. In the following piece of code, we only read _bool, not the returned _number and _array:
(, _bool2, ) = returnNamed();

Verify on remix

  • View the results of the three return methods after deploying the contract

Solidity minimalist entry #4. Function output _ethereum

Summarize

In this lecture, we introduce the return value return and returns of the function, including: returning various variables, named return, and using destructuring assignment to read all or part of the return value.

Supongo que te gusta

Origin blog.csdn.net/u010359479/article/details/128891397
Recomendado
Clasificación