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

Can a Golang function return multiple values?

PHPz
Release: 2024-04-13 14:42:01
Original
792 people have browsed it

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
}
Copy after login

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
}
Copy after login

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)
}
Copy after login

Output:

Minimum: 1
Maximum: 5
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template