如何在 Golang 中從函式返回多個值?
在本教程中,我們將瞭解如何在 Golang 中使用演算法和示例從函式返回多個值。像 Python 等其他程式語言一樣,Golang 也支援從函式返回多個值。在第一個示例中,我們將向函式傳遞兩個數字,並一起返回較小的數字,然後是較大的數字。在第二個示例中,我們傳遞兩個數字並一次返回加法、減法、乘法和除法。
語法
Func functionName(arguments) (returnType1, returnType2, …) {
// logic
return returnTypeVariable1, returnTypeVariable2, …
}
解釋
(returnType1, returnType2, …) - 在此程式碼行中,returnType1 和 returnType2 的位置可以填寫我們返回值的資料型別。
return returnTypeValue1, returnTypeValue2, … - 在這裡,我們返回各自資料型別的變數。
演算法
步驟 1 - 宣告變數。
步驟 2 - 初始化變數。
步驟 3 - 呼叫返回多個值的函式。
步驟 4 - 列印結果。
示例 1
在這個示例中,我們將呼叫一個函式,並將兩個整數作為引數傳遞。此函式將首先返回較小的數字,然後是較大的數字。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func smallerNumber(number1, number2 int) (int, int) {
if number1 < number2 {
return number1, number2
}
return number2, number1
}
func main() {
// declaring the variable
var number1, number2 int
// initializing the variable
number1 = 10
number2 = 21
fmt.Println("Golang program to return the multiple values from the function in Golang.")
// calling the recursive function
smaller, bigger := smallerNumber(number1, number2)
fmt.Println("The smaller number is", smaller)
fmt.Println("The bigger number is", bigger)
}
輸出
Golang program to return the multiple values from the function in Golang. The smaller number is 10 The bigger number is 21
示例 2
在這個示例中,我們將編寫一個函式,該函式將一次返回加法、減法、乘法和除法。這種方法將減少程式中函式呼叫的次數。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func addSubMulDiv(number1, number2 int) (int, int, int, int) {
var addition, subtraction, multiplication, division int
// adding two numbers
addition = number1 + number2
// subtracting two numbers
subtraction = number1 - number2
// multiplying two numbers
multiplication = number1 * number2
// dividing two numbers
division = number1 / number2
return addition, subtraction, multiplication, division
}
func main() {
// declaring the variable
var number1, number2 int
// initializing the variable
number1 = 100
number2 = 20
fmt.Println("Golang program to return the multiple values from the function in Golang.")
// calling the recursive function
addition, subtraction, multiplication, division := addSubMulDiv(number1, number2)
fmt.Printf("The addition of %d and %d is %d.\n", number1, number2, addition)
fmt.Printf("The subtraction of %d and %d is %d.\n", number1, number2, subtraction)
fmt.Printf("The multiplication of %d and %d is %d.\n", number1, number2, multiplication)
fmt.Printf("The division of %d and %d is %d.\n", number1, number2, division)
}
輸出
Golang program to return the multiple values from the function in Golang. The addition of 100 and 20 is 120. The subtraction of 100 and 20 is 80. The multiplication of 100 and 20 is 2000. The division of 100 and 20 is 5.
結論
這就是在 Golang 中使用兩個示例從函式返回多個值的方法。要了解有關 Golang 的更多資訊,您可以瀏覽這些教程。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP