Go function type, reusable function signatures

How to learn a new programming language by having the compiler yelling at you

Jaga Santagostino
Jan 21, 2018 · 1 min read

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)
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade