Methods
Value receivers
A method is a function with a receiver argument before the name.
type Counter struct{ N int }
func (c Counter) Value() int {
return c.N
}
Pointer receivers
Use a pointer when the method should update the receiver or avoid copying.
func (c *Counter) Inc() {
c.N++
}
c := Counter{}
c.Inc()
fmt.Println(c.Value())
Choose consistently
If any method needs a pointer receiver, often make related methods pointer receivers too.
Method habits
- Receivers are usually one or two letters from the type name
- Exported methods start with a capital letter
- Methods work with structs you define in the same package
- Interfaces (next) are satisfied implicitly by method sets
Comments
One comment per signed-in account. Comments are saved with this page’s URL.