Solidity - 函式



函式是一組可重用的程式碼,可以在程式的任何地方呼叫。這避免了重複編寫相同程式碼的需要,有助於程式設計師編寫模組化程式碼。函式允許程式設計師將大型程式分解成許多小型且易於管理的函式。

與任何其他高階程式語言一樣,Solidity 也支援使用函式編寫模組化程式碼所需的所有功能。本節解釋如何在 Solidity 中編寫您自己的函式。

函式定義

在使用函式之前,我們需要定義它。在 Solidity 中定義函式最常見的方法是使用 **function** 關鍵字,後跟唯一的函式名、引數列表(可能為空)以及用大括號括起來的語句塊。

語法

基本語法如下所示。

function function-name(parameter-list) scope returns() {
   //statements
}

示例

嘗試以下示例。它定義了一個名為 getResult 的函式,該函式不接受任何引數:

pragma solidity ^0.5.0;

contract Test {
   function getResult() public view returns(uint){
      uint a = 1; // local variable
      uint b = 2;
      uint result = a + b;
      return result;
   }
}

呼叫函式

要在合約中的其他地方呼叫函式,只需編寫該函式的名稱,如下面的程式碼所示。

嘗試以下程式碼來了解字串在 Solidity 中的工作方式。

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);//access local variable
   }
}

使用Solidity 第一個應用章節中提供的步驟執行上述程式。

輸出

0: string: 3

函式引數

到目前為止,我們已經看到了沒有引數的函式。但是,在呼叫函式時,可以傳遞不同的引數。這些傳遞的引數可以在函式內部捕獲,並且可以對這些引數進行任何操作。函式可以接受多個引數,引數之間用逗號分隔。

示例

嘗試以下示例。我們在這裡使用了 **uint2str** 函式。它接受一個引數。

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);//access local variable
   }
}

使用Solidity 第一個應用章節中提供的步驟執行上述程式。

輸出

0: string: 3

return 語句

Solidity 函式可以包含可選的 **return** 語句。如果您想從函式返回一個值,則需要此語句。此語句應是函式中的最後一條語句。

如上例所示,我們使用 uint2str 函式返回一個字串。

在 Solidity 中,函式也可以返回多個值。請參見下面的示例:

pragma solidity ^0.5.0;

contract Test {
   function getResult() public view returns(uint product, uint sum){
      uint a = 1; // local variable
      uint b = 2;
      product = a * b;
      sum = a + b;
  
      //alternative return statement to return 
      //multiple values
      //return(a*b, a+b);
   }
}

使用Solidity 第一個應用章節中提供的步驟執行上述程式。

輸出

0: uint256: product 2
1: uint256: sum 3
廣告
© . All rights reserved.