Go function type, reusable function signatures
How to learn a new programming language by having the compiler yelling at you
1 min readJan 21, 2018
I was looking for a way to reuse a common signature in various functions in Golang, googling for while I had no luck.
I tried the “heuristic way” of writing random code to let the compiler give me some hopefully useful hints so I started with what I felt could be right.
And after a couple tries……. it worked.
You can declare a function signature as a type
type myFunctionType = func(a, b string) string
An example:
package mainimport "fmt"type myFunctionType = func(a, b string) stringfunc main() {
var explicit myFunctionType = func(a, b string) string {
return fmt.Sprintf("%s %s", a, b)
}implicit := func(a, b string) string {
return fmt.Sprintf("%s %s", b, a)
}functionTypeConsumer(explicit)
functionTypeConsumer(implicit)
functionTypeConsumer(func(a, b string) string {
return fmt.Sprintf("%s %s!", a, b)
})}func functionTypeConsumer(fn myFunctionType) {
s := fn("hello", "world")
fmt.Println(s)
}
Here a working example on Go playground