I'm new to Go, and I was going over a couple of written pieces of code, and noticed a lot of them had functions initialized as
type Foo func() foo
where Foo
is the type name, and foo
is the return type. I was wondering what the point of this is?
In Go, functions are first-class types; they can be parameters to other functions, returned from functions, or used as struct
fields, map
values, slice elements, and so on. Defining a named function type makes it easier to do this, as you'd likely see in any code where you've seen this pattern. You can also define methods on these types (yes, a function type can have methods defined on it!), such as is done with net/http
's HandlerFunc
.