Methods
A method is a function with a receiver argument written before the name: func (s Session) Expired() bool. The receiver type is any named type in the same package, not only a struct.
Detailed Explanation
Go does not put functions inside a class body. You declare a type, then you declare methods next to it, often in the same file. func (s Session) Expired() bool is a function that takes a Session as its first argument and is called as s.Expired(). The extra syntax exists so the method belongs to the type's method set, which is what interfaces look at.
The receiver is an argument. s is a name you choose, usually a short letter, not this or self. A value receiver gets a copy. A pointer receiver gets an address. Choosing between them is the whole of the next term, receivers. You can call a pointer-receiver method on an addressable value: s.Expired() becomes (&s).Expired() when needed.
Any named type can have methods. type Count int plus func (c Count) Inc() Count is legal. type HandlerFunc func(http.ResponseWriter, *http.Request) plus a ServeHTTP method is how the standard library turns a function into an http.Handler. You cannot attach methods to a type defined in another package, including predeclared types. func (s string) Trim() does not compile.
There is no implicit this promotion beyond embedding. A method sees the receiver and what you pass. Fields of the receiver are s.Token. Methods of an embedded type are promoted onto the outer type, which is embedding, not inheritance.
Method values and expressions. s.Expired is a function func() bool that holds s. Session.Expired is a function func(Session) bool. The first is what you pass to errgroup. The second is useful in tests and adapters.
What it costs. A method call is a function call. A value receiver copies the receiver; a large struct should use a pointer. Methods are also API: renaming Expired breaks every interface that required it. Keep the method set small and named for the behaviour callers need, not for every field.
Code Examples
package main
import (
"fmt"
"time"
)
type Session struct {
Expires time.Time
}
func (s Session) Expired() bool {
return time.Now().After(s.Expires)
}
func main() {
s := Session{Expires: time.Now().Add(-time.Hour)}
fmt.Println(s.Expired())
}type Count int
func (c Count) Inc() Count { return c + 1 }func (s Session) String() string {
return s.Expires.Format(time.RFC3339)
}Common Gotchas
Methods must live in the same package as the type
you cannot extend `time.Time` with a method in your package. Write a function, or embed `time.Time` in your own type.
A method value captures the receiver
later changes to a value receiver's copy are not seen; a pointer receiver is.
The receiver name should not be `this` or `self`
convention is a one- or two-letter abbreviation of the type.
`String() string` is the fmt contract
implement it when the default `%v` dump is not what you want in logs.