Home  >  Article  >  Backend Development  >  Can a Golang function return multiple values?

Can a Golang function return multiple values?

PHPz
PHPzOriginal
2024-04-13 14:42:01761browse

Yes, Go functions can return multiple values ​​by returning a tuple, which is an immutable value that can contain different types of data.

Golang 函数可以返回多个值吗?

#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn