Home > Backend Development > Golang > Can Go's `fmt.Println` Handle Multiple Return Values from a Function Directly?

Can Go's `fmt.Println` Handle Multiple Return Values from a Function Directly?

Susan Sarandon
Release: 2024-12-15 07:57:14
Original
285 people have browsed it

Can Go's `fmt.Println` Handle Multiple Return Values from a Function Directly?

Passing Multiple Return Values to Variadic Functions in Go

Question:

Can a function returning multiple integer values be directly passed into fmt.Println() for formatted string output, similar to Python?

func temp() (int, int) { return 1, 1 }
fmt.Println("first= %d and second = %d", temp()) // Not supported
Copy after login

Answer:

No, this is not directly supported by default in Go. According to the language specification, "Calls" expects a function call as the sole argument for variadic parameters like ...interface{}, and functions must have at least one return value.

fmt.Printf(), however, allows for a format string alongside the variadic parameter, making it more suitable for this task. However, since temp() returns a tuple, it cannot be directly passed as a ...interface{} argument.

Solution:

To pass multiple return values into a variadic function, a utility wrapper function can be used to convert the tuple into a []interface{} slice, which can then be passed as the variadic argument. Below is an example implementation:

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

Using this wrapper function, the temp() function can now be passed into fmt.Printf():

func main() {
    fmt.Printf("first= %v and second = %v", wrap(temp()...)...)
}
Copy after login

This will properly print the values of temp().

The above is the detailed content of Can Go's `fmt.Println` Handle Multiple Return Values from a Function Directly?. 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