Home >Backend Development >Golang >How to Pass Multiple Return Values to a Variadic Function in Go?

How to Pass Multiple Return Values to a Variadic Function in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 19:53:10722browse

How to Pass Multiple Return Values to a Variadic Function in Go?

Passing Multiple Return Values to a Variadic Function

Problem:

You have a Go function that returns two integers and want to print both values using string formatting within a fmt.Println() call. However, this approach is not supported by default in Go.

Solution:

While you can't directly pass multiple return values to fmt.Println(), you can use a trick to achieve the same result with fmt.Printf():

  1. Create a utility function, wrap(), that takes variable numbers of inputs and returns a slice of []interface{}.
  2. Call wrap() with the return values of your function, passing them as individual parameters.
  3. Pass the resulting slice to fmt.Printf() as the value for variadic parameter ....

Here's an example:

func wrap(vs ...interface{}) []interface{} {
    return vs
}

func twoInts() (int, int) {
    return 1, 2
}

func main() {
    fmt.Printf("first= %d and second = %d", wrap(twoInts()...)...)
}

This approach allows you to pass multiple return values to a variadic function, enabling you to print them using string formatting within fmt.Printf().

Note:

  • fmt.Println() can still be used with functions that return at least one value, as it automatically assigns the excess return values to its variadic parameter.
  • The wrap() utility function can be generalized to handle functions with any number of return values.
  • For additional insights, refer to related questions on multiple values in single-value contexts and returning map-like 'ok' values in Go functions.

The above is the detailed content of How to Pass Multiple Return Values to a Variadic Function in Go?. 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