Solidity 函数

函数是一组可重用代码的包装,接受输入,返回输出。

Solidity 支持函数定义和调用。

1. 函数定义

Solidity中, 定义函数的语法如下:

语法

function function_name(<parameter list>) <visibility> <state mutability> [returns(<return type>)] {
    //语句
}

函数由关键字function声明,后面跟函数名、参数、状态可变性、可见性、返回值的定义。

可见性(visibility)

函数的可见性有四种:

  • Private(私有):函数只能在所定义的智能合约内部调用。
  • Internal(内部):可以在所定义智能合约内部调用该函数,也可以从继承合约中调用该函数。
  • External(外部):只能从智能合约外部调用。 如果要从智能合约中调用它,则必须使用 this。
  • Public(公开):可以从任何地方调用。

状态可变性(mutability)

  • view:用view声明的函数只能读取状态,而不能修改状态。
  • pure:用pure声明的函数既不能读取也不能修改状态。
  • payable:用payable声明的函数可以接受发送给合约的以太币,如果未指定,该函数将自动拒绝所有发送给它的以太币

示例

下面的例子,定义了一个名为getResult的函数,该函数不接受任何参数:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
   function getResult() public view returns(uint){
      uint a = 1; // 局部变量
      uint b = 2;
      uint result = a + b;
      return result;
   }
}

2. 函数调用

要调用函数,只需使用函数名,并传入参数即可。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SolidityTest {
   constructor() {
   }
   
   function getResult() public pure returns(string memory){
      return integerToString(3);  // 调用函数 integerToString
   }
   
  // integerToString 函数定义
function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } }

运行上述程序,输出:

0: string: 3

3. return 语句

Solidity中, 函数可以返回多个值。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
   function getResult() public view returns(uint product, uint sum){
      uint a = 1; // 局部变量
      uint b = 2;
      product = a * b; // 使用返回参数返回值
      sum = a + b; // 使用返回参数返回值

      // 也可以使用return返回多个值
      // return(a*b, a+b);
   }
}

运行上述程序,输出:

0: uint256: product 2
1: uint256: sum 3

Solidity 函数的返回值可以使用名字,也可以采用匿名方式。Solidity 函数的返回值可以通过名字赋值,也可以使用 return 返回。Solidity 函数支持多个返回值。// SPDX-Licens ...