Functional parameters in Go functions

Is there a way to pass a function(which can be generic) to another function?

You can pass functions to functions if their type matches. As go has no generics you can’t pass generic functions, but only those that match the concrete type.

is there a way in which I can specify the type of function runtime?

func(string)string is the type of a function that takes and returns a string.

So the following will take a function of that kind and a string and then return the result of applying the function on that string:

def foo(s string, f func(string)string) string {
  return f(s)
}

let
some_fun(a int, b int)x int{
x = a+b
return
}
some_fun2(a string, b string)x string{
x = a+b
return
}
someanother_fun(){
}
main(){
someanother_fun(some_fun)
someanother_fun(some_fun2)
}

is there a way to design someanother_fun() such that it takes input at runtime both the types and inputs?
or any way closer to this way also helps

Whatever it is you have posted, but it can’t work.

someanother_fun does not accept any arguments, still you call it twice with one argument. And as some_fun and some_fun2 have different types (at least it looks like that, I am not sure what the x is supposed to be…) they can not be passed to a function accepting a func()-like type.

You can use an interface{} and type assertions/switches though, but thats giving up compiletime typesafety.

Go has no Generics, and it will probably not have them before Go 2.0.

ok thanks for fast reply

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.