如何在 Golang 中建立沒有引數但返回值的函式?
本教程將教我們如何建立一個沒有引數但有返回值的函式。本教程涉及函式的要點,以及在 Golang 中沒有引數且有返回型別的函式的語法,最後我們將看到兩個沒有引數且有返回型別的函式的不同示例。在這兩個示例中,我們將建立兩個函式,它們在被呼叫時都會返回一個字串。
無引數且有返回型別的函式。
語法
現在我們將看到無引數且有返回型別的函式的語法和解釋。
func functionName( ) (returnType1, returnType2, …) { return returnValue1, returnValue2, … }
解釋
func 是 Golang 中的關鍵字,它告訴編譯器已定義了一個函式。
在函式名稱旁邊,我們編寫函式的名稱,該名稱必須以字母開頭。
現在我們將編寫空的花括號 (),因為我們不希望函式帶有引數。
要提及返回型別,我們將在引數聲明後的單獨的花括號 () 中編寫它們。
在大括號之間,我們可以編寫函式的邏輯。
編寫完所有邏輯後,我們將使用 return 關鍵字返回我們想要返回的所有值。
演算法
步驟 1 - 開始 main() 函式。
步驟 2 - 呼叫無引數且有返回值的函式,並將值儲存在相應的變數中。
步驟 3 - 宣告函式,在函式體中編寫邏輯,並在最後返回該值。
步驟 4 - 對函式返回的值執行所需的操作。
示例 1
在這個例子中,我們建立了兩個函式 FirstSmall() 和 SecondSmall(),如果第一個數字小或第二個數字小,則分別返回被呼叫的字串。
package main import ( // fmt package provides the function to print anything "fmt" ) func FirstSmall() string { return "First number is smaller than the second." } func SecondSmall() string { return "Second number is smaller than the first." } func main() { // declaring the variables var firstNumber, secondNumber int // initializing the variable firstNumber = 10 secondNumber = 8 fmt.Println("Golang program to learn how to create a function without argument but with return value.") fmt.Println("Comparing the numbers and printing the message by calling a function.") if firstNumber < secondNumber { fmt.Println(FirstSmall()) } else { fmt.Println(SecondSmall()) } }
輸出
Golang program to learn how to create a function without argument but with return value. Comparing the numbers and printing the message by calling a function. Second number is smaller than the first.
示例 2
在這個例子中,我們建立了兩個函式 evenNumber() 和 oddNumber(),如果數字是偶數或數字是奇數,則分別返回被呼叫的字串。
package main import ( // fmt package provides the function to print anything "fmt" ) func evenNumber() string { return "Number is even." } func oddNumber() string { return "Number is odd." } func main() { // declaring and initializing the array numberArray := [5]int{32, 45, 67, 3, 88} fmt.Println("Golang program to learn how to create a function without argument but with return value.") fmt.Println("Checking the array element is odd or even.") // running for loop on the array for i := 0; i < 5; i++ { // checking the number at index i is odd or even if numberArray[i]%2 == 0 { fmt.Println(numberArray[i], evenNumber()) } else { fmt.Println(numberArray[i], oddNumber()) } } }
輸出
Golang program to learn how to create a function without argument but with return value. Checking the array element is odd or even. 32 Number is even. 45 Number is odd. 67 Number is odd. 3 Number is odd. 88 Number is even.
結論
這兩個是無引數且有返回值的函式的示例。這些型別函式的主要用例是,如果您想多次執行相同型別的某些操作並返回相同的值,那麼我們可以建立一個無引數且有返回值的函式。要了解有關 Golang 的更多資訊,您可以瀏覽這些教程。
廣告