如何在Go語言中建立帶引數但無返回值的函式?


本教程將教你如何建立一個帶引數但無返回值的函式。本教程包括關於函式的要點,以及Go語言中帶引數且無返回值函式的語法,最後我們將看到兩個帶引數但無返回值函式的不同示例。在第一個示例中,我們將列印傳遞給函式的引數以及相應的語句。在另一個示例中,我們將新增作為引數傳遞的數字,並在同一個函式中列印它們的和。

帶引數且無返回值的函式。

語法

現在我們將看到帶引數且無返回值函式的語法和解釋。

func functionName(argumentName1 argumentType, argumentName2 argumentType, …) {
}

解釋

  • func是Go語言中的關鍵字,它告訴編譯器定義了一個函式。

  • 緊跟在函式關鍵字後面的是函式名,函式名必須以字母開頭。

  • 現在,我們將引數寫在圓括號()中,引數名和資料型別寫在引數名後面。

  • 因為我們不需要任何返回值,所以我們不會在圓括號和花括號之間寫任何內容。

  • 在花括號內,我們可以編寫函式的邏輯。

演算法

  • 步驟1 - 定義要傳遞給函式的變數。

  • 步驟2 - 初始化變數。

  • 步驟3 - 使用相應的引數呼叫函式。

  • 步驟4 - 宣告函式並在函式體中編寫邏輯。

示例1

在這個例子中,我們傳遞一個表示芒果數量的引數,然後在帶引數且無返回值的函式中列印它們。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)

// declare the function with argument and without return value
func PrintTotalMangoes(numberOfMangoes int) {
   fmt.Println("The total number of mangoes is ", numberOfMangoes)
}
func main() {

   // declaring the variable
   var numberOfMangoes int
   
   // initializing the variable
   numberOfMangoes = 10
   fmt.Println("Golang program to learn how to create a function with an argument but no return value.")
   fmt.Println("Print the total number of mangoes.")
   
   // calling the function with arguments
   PrintTotalMangoes(numberOfMangoes)
}

輸出

Golang program to learn how to create a function with an argument but no return value.
Print the total number of mangoes.
The total number of mangoes is 10

示例2

在這個例子中,我們傳遞兩個引數,這兩個引數的值是兩個數字,我們將它們的和在帶引數且無返回值的函式中打印出來。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)

// declare the function with argument and without return value
func Addition(number1, number2 int) {

   // declaring the variable
   var number3 int
   
   // adding value of two variables and storing in the third variable
   number3 = number1 + number2
   fmt.Printf("The addition of %d and %d is %d.\n", number1, number2, number3)
}
func main() {

   // declaring the variables
   var number1, number2 int
   
   // initializing the variable
   number1 = 10
   number2 = 8
   fmt.Println("Golang program to learn how to create a function with an argument but no return value.")
   fmt.Println("Print the addition of two numbers.")
   
   // calling the function with arguments
   Addition(number1, number2)
}

輸出

Golang program to learn how to create a function with an argument but no return value.
Print the addition of two numbers.
The addition of 10 and 8 is 18.

結論

以上是兩個帶引數且無返回值函式的示例。這類函式的主要用例是:如果你想在一個函式中對變數執行某些操作,並希望在同一個函式中列印結果,那麼帶引數且無返回值的函式是正確的選擇。要了解更多關於Go語言的知識,你可以瀏覽這些教程。

更新於:2023年1月17日

瀏覽量:277

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告