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

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

Susan Sarandon
Release: 2024-12-09 08:55:06
Original
1028 people have browsed it

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

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

Background:
Go functions can return multiple values, but standard variadic function calls do not allow for passing those values directly. This article explores a method to achieve this using a custom wrapper function.

Problem:
Consider a function that returns two integer values:

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

We want to pass these return values to the variadic Printf function to print them using string formatting:

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

Solution:

1. Direct Approach (Not Supported):
The standard function call syntax does not support passing multiple return values to a variadic function. This is because variadic parameters must be the last parameters in a function signature.

2. Wrap Return Values:
We can create a wrapper function that converts the return values of any function into a []interface{} slice. The variadic Printf function can then accept this slice as its arguments.

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

Usage:
Using the wrap function, we can now pass the return values of our temp function to Printf:

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

Additional Notes:

  • This technique can be used to pass multiple return values to any variadic function in Go.
  • The fmt.Println function can also be used to print multiple return values directly, but it does not support string formatting.

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