Home > Backend Development > Golang > How to Handle Multiple Return Values When Passing to Variadic Functions in Go?

How to Handle Multiple Return Values When Passing to Variadic Functions in Go?

Mary-Kate Olsen
Release: 2024-12-18 21:56:14
Original
713 people have browsed it

How to Handle Multiple Return Values When Passing to Variadic Functions in Go?

Multiple Return Values with Variadic Functions

Suppose you have a Go function that returns multiple integer values, such as:

func temp() (int, int) {
    return 1, 1
}
Copy after login

Intuitively, you might want to directly pass the result of temp to Printf and print both values using string formatting:

fmt.Printf("first= %d and second = %d", temp())
Copy after login

However, this approach does not work because temp returns two values, while Printf expects only one.

The reason for this limitation lies in the Go function call specification. It states that if a function has a final ... parameter (as Printf does), it can only be assigned the remaining return values of another function. This implies that the other function must have at least one return value.

Using String Interpolation

Instead of using Printf, you can leverage string interpolation to achieve your goal:

a, b := temp()
fmt.Println("first=", a, "and second =", b)
Copy after login

Wrapping Return Values

To pass multiple return values to a variadic function like Printf, you can utilize a utility function called wrap. It takes an arbitrary number of interface{} values and returns a slice of interface{} values:

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

With this utility, you can pass the return values of any function that has at least one return value to wrap and use the resulting slice to call Printf:

fmt.Printf("1: %v, 2: %v\n", wrap(oneInt())...)
fmt.Printf("1: %v, 2: %v\n", wrap(twoInts())...)
fmt.Printf("1: %v, 2: %v, 3: %v\n", wrap(threeStrings())...)
Copy after login

where oneInt, twoInts, and threeStrings are functions returning single integers, tuples of integers, and tuples of strings, respectively.

This approach bypasses the restriction of passing only one return value to variadic functions, allowing you to print the multiple return values of your functions as desired.

The above is the detailed content of How to Handle Multiple Return Values When Passing to Variadic Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template