Reputation: 1446
I'm trying to create a func that accepts and returns any number of arguments. I came across anoymous functions:
func AWSApiRetry(awsFunc func()) {
return awsFunc()
}
This allows me to call a func:
AWSApiRetry(func() {
GetEnvState(sess, ApplicationName, EnvName)
})
but when I try to retrieve the return values from GetEnvState which are (string, err):
ElbReady, err := AWSApiRetry(func() {
GetEnvState(sess, ApplicationName, EnvName)
})
I'm getting the error: AWSApiRetry(func literal) used as value
How can I use my AwsApiretry func to return those types anonymously. It can be any number and type of return values, so it just sort of 'pass-through' and returns whatever the func being called returns.
Upvotes: 0
Views: 1526
Reputation: 775
This question is roughly a year old, but no one has correctly identified the problem: the AWSApiRetry() function signature has no return. You cannot assign the return value of a function having no return value.
The actual API you're aiming to offer, defining a function with an arbitrary signature, can be accomplished using the function MakeFunc(), in the standard reflect package.
If you wanted to get more specific about the needs you observed, I'd be happy to propose a specific solution.
Upvotes: 0
Reputation:
Does this help answer part of your question?
package main
import "fmt"
func main() {
GetEnvState := func(i ...int) {
fmt.Println(i)
}
AwsApiretry := func(awsFunc func()) {
awsFunc()
}
AwsApiretry(func() { GetEnvState(1) }) // prt [1]
AwsApiretry(func() { GetEnvState(1, 2) }) // prt [1 2]
//ElbReady := AwsApiretry(func() { GetEnvState(1, 2, 3) })
//fmt.Println(ElbReady) // AwsApiretry(func literal) used as value
}
But I also agree with @Cerise and @Kelsnare terrific answers. It is not possible to call a function/method that returns an unknown type. When ElbReady is added you get an error:
AwsApiretry(func literal) used as value
Upvotes: 0
Reputation: 705
You cannot.
AFAIK, in its current form, go is statically typed. What you want to do is create a function/method that returns types not known during compile time. go, by design, does not allow you to create a function/method like that
Upvotes: 1