Methods aren't for "objects"
July 24, 2023
I’ll be livestreaming again today, in just a few minutes. Join me live, or watch the replay. I’ll be picking up where I left off, with my new linter project.
One of the most powerful things I like about Go, is the ability to put methods on any type.
Type definitions
…
Type definitions may be used to define different boolean, numeric, or string types and associate methods with them:
type TimeZone int const ( EST TimeZone = -(5 + iota) CST MST PST ) func (tz TimeZone) String() string { return fmt.Sprintf("GMT%+dh", tz) }
In many other languages, if you want to associated a method with, say, an integer, you have to wrap that integer in an Object. Not so in Go. With Go, you can just define a custom type, with an underlying type of int
, and put methods on it!
You can even put methods on funcion types, which seems a bit strange at first, but is also very powerful. There’s actually a good chance you’ve already used this pattern, perhaps without realizign it, if you use the net/http
pacakge. The type HandlerFunc
is such an example:
type HandlerFunc func(ResponseWriter, *Request)
This type, which is a function type, has a single method defined on it:
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
Quotes from The Go Programming Language Specification Version of December 15, 2022