Functions and Methods
Pointer Receivers
Pointer receiver methods can update the value they are called on.
Pointer Receivers
pointer_receiver.go
package main
import "fmt"
type Counter struct {
Value int
}
func (c *Counter) Add(delta int) {
c.Value += delta
}
func main() {
var step =
counter := Counter{Value: 2}
counter.Add(step)
fmt.Println("step=", step)
fmt.Println("value=", counter.Value)
}
package main
import "fmt"
type Counter struct {
Value int
}
func (c *Counter) Add(delta int) {
c.Value += delta
}
func main() {
var step =
counter := Counter{Value: 2}
counter.Add(step)
fmt.Println("step=", step)
fmt.Println("value=", counter.Value)
}
package main
import "fmt"
type Counter struct {
Value int
}
func (c *Counter) Add(delta int) {
c.Value += delta
}
func main() {
var step =
counter := Counter{Value: 2}
counter.Add(step)
fmt.Println("step=", step)
fmt.Println("value=", counter.Value)
}
pointer receiver
A method with a pointer receiver can modify fields on the original value.