Passing Function Return Values as Inputs to Another Function
In Go, you can conveniently pass the return values of one function as input arguments to another function. For example:
func returnIntAndString() (i int, s string) {...}
func doSomething(i int, s string) {...}
doSomething(returnIntAndString())
However, complications arise when you add an additional argument to the second function:
func doSomething(msg string, i int, s string) {...}
doSomething("message", returnIntAndString()) // Error
The error message indicates that you cannot pass multiple return values to a function expecting a single argument.
Solution
As per the Go specification, a function can only pass its return values as input arguments to another function if the latter expects the exact same number of arguments. There is no mechanism for passing extra parameters in this scenario.
Therefore, to resolve the issue, you have two options:
func doSomethingVariadic(msg string, args ...interface{}) {
// Code to handle variable number of arguments
}
You can then call this function with the desired arguments, including the return values of returnIntAndString():
doSomethingVariadic("message", returnIntAndString())
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3