Home >Backend Development >Golang >How Can I Print Multiple Return Values from a Go Function Using fmt.Printf()?

How Can I Print Multiple Return Values from a Go Function Using fmt.Printf()?

DDD
DDDOriginal
2024-12-10 13:45:16585browse

How Can I Print Multiple Return Values from a Go Function Using fmt.Printf()?

Passing Multiple Return Values to Variadic Functions

In Go, a function can return multiple values. However, directly assigning the return values of a function to a format string in a call to fmt.Println() is not possible by default.

Approach Using fmt.Printf()

To achieve the desired behavior, fmt.Printf() should be used instead of fmt.Println(). However, passing additional parameters besides the function call is not allowed by the specification for variadic function calls.

Using a Wrapper Function

To bypass this restriction, a wrapper function can be employed. The wrap() function takes multiple values and returns them as a slice of interface{} values. This allows us to pass the return values of any function with at least one return value to fmt.Printf().

Example

Output

Conclusion

By using the wrap() function, it is possible to pass multiple return values of a function to a variadic function like fmt.Printf(). This provides a simple and convenient way to format and print the results of a function call.

The above is the detailed content of How Can I Print Multiple Return Values from a Go Function Using fmt.Printf()?. 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