Hi, I need a function that can accept any function in parameter. My problem is, when I run my function " genFunc " with a function that has a parameter, it doesn’t work. I need to define my func type again ( anyFunc ) with parameter ( type anyFunc func(string) ). Is there a way to define a type function that accept any function?
package main
import (
"fmt"
)
type anyFunc func()
func helloFunc() {
fmt.Println("Hello world!")
}
func genFunc(gfunc anyFunc) {
gfunc()
}
func main() {
genFunc(helloFunc) // Print "Hello world!"
genFunc(func(name string){
// Not working...
}) // cannot use func literal (type func(string)) as type anyFunc in argument to genFunc
}
I mean, I need to define my function with parameter.
e.g: type anyFunc func(string) to accept a function with parameter.
func main() {
genFunc(helloFunc) // Print "Hello world!"
genFunc(func(name string){
// Not working...
}) // cannot use func literal (type func(string)) as type anyFunc in argument to genFunc
}
Go’s type system is static and quite strict, and so func() is a different type than func(string). Besides that, even if you could pass a func(string) to genFunc, then genFunc would need a way to determine how many parameters that function expects, and pass those parameters to that function.
What do you want to achieve through this approach? I can imagine there are other ways of doing what you need to do.
What goal do you want to achieve with this construct that cannot be achieved otherwise?
If you want to build sophisticated language constructs, Go is perhaps not the right language for that. In a dynamically typed language, things like this are usually much easier to achieve.
If you want to solve a real-world problem, then there are surely other ways to do this.
Yeah your right, there are many ways to do this. I just created this construct to look like similar to GCD on iOS. I found out that method chaining through interface can achieve this. sounds crazy but I want to create my own package with this kind of construct. but anyway thanks a lot @christophberger