Yes, Go functions can return multiple values by returning a tuple, which is an immutable value that can contain different types of data.
#Can a Go function return multiple values?
Go functions can return multiple values by returning a tuple. A tuple is an immutable value that can contain different types of data.
Syntax:
func functionName() (returnType1, returnType2, ..., returnTypeN) { // ... return value1, value2, ..., valueN }
Example:
func getMinMax(numbers []int) (int, int) { min := numbers[0] max := numbers[0] for _, n := range numbers { if n < min { min = n } if n > max { max = n } } return min, max }
Let us use a practical case to demonstrate how to use return multiple values Function:
Case: Find the maximum and minimum value in an array
package main import "fmt" func getMinMax(numbers []int) (int, int) { min := numbers[0] max := numbers[0] for _, n := range numbers { if n < min { min = n } if n > max { max = n } } return min, max } func main() { numbers := []int{1, 3, 5, 2, 4} min, max := getMinMax(numbers) fmt.Println("Minimum:", min) fmt.Println("Maximum:", max) }
Output:
Minimum: 1 Maximum: 5
In this case, The getMinMax
function returns a tuple containing the minimum and maximum values in the array. The main function then gets the returned value by unpacking the tuple.
The above is the detailed content of Can a Golang function return multiple values?. For more information, please follow other related articles on the PHP Chinese website!