Methods
Methods in Go.
- A method is a function with a receiver argument
func (recv <type>) fn()
- The type a method belongs to is known as the receiver
- The type must be delared in the same package as the function.
- Pointer receivers
func (recv *<type>)
should be used when the function needs to modify the receiver.
Example Methods
package main
// Item is a thing
type Item struct {
Name string
Qty int
cfg string
}
// GetCfg gets the configuration string of the Item
func (i *Item) GetCfg() string {
return i.cfg
}
// SetCfg sets a configuration string on the Item
func (i *Item) SetCfg(cfg string) *Item {
i.cfg = cfg
return i
}
func main() {
}
Constructors
Allocation with new allows you to construct a Type.
item := new(Item)
You can create constructor functions as follows:
func NewItem() *Item {
item := new(Item)
// Perform operations on item here.
return item
}
Construct a new item as follows:
item := NewItem()
Example Code
Resources
- Effective Go: Methods
- Effective Go: Functions
- Go by Example: Functions
- Best Practices / Patterns