Solidity教程

Solidity 函数

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

函数定义

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

语法

function function-name(parameter-list) scope returns() {
   //语句
}
函数由关键字 function声明,后面跟函数名、参数、可见性、返回值的定义。

示例

下面的例子,定义了一个名为 getResult的函数,该函数不接受任何参数:
pragma solidity ^0.5.0;
contract Test {
   function getResult() public view returns(uint){
      uint a = 1; // 局部变量
      uint b = 2;
      uint result = a + b;
      return result;
   }
}

函数调用与函数参数

要调用函数,只需使用函数名,并传入参数即可。
pragma solidity ^0.5.0;
contract SolidityTest {
   constructor() public{
   }
   function getResult() public view returns(string memory){
      uint a = 1;
      uint b = 2;
      uint result = a + b;
      return integerToString(result); // 调用函数
   }
   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);// 访问局部变量
   }
}
可以参考Solidity – 第一个程序中的步骤,运行上述程序。
输出
0: string: 3

return 语句

Solidity中, 函数可以返回多个值。
pragma solidity ^0.5.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);
   }
}
可以参考Solidity – 第一个程序中的步骤,运行上述程序。
输出
0: uint256: product 2
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4