go / beginner
Snippet
Methods with Pointer Receivers
Methods can be defined with value receivers `(*Counter)` or pointer receivers. Pointer receivers modify the original struct, while value receivers work on a copy. For mutable operations, always use pointer receivers.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package mainimport "fmt"type Counter struct {value int}func (c *Counter) Increment() {c.value++}func (c Counter) Value() int {return c.value}func (c *Counter) Add(n int) {c.value += n}func main() {c := Counter{value: 10}c.Increment()c.Add(5)fmt.Printf("Counter: %d\n", c.Value())}
Breakdown
1
func (c *Counter) Increment()
Pointer receiver allows mutation of c.value
2
func (c Counter) Value() int
Value receiver, safe for read-only operations
3
c.Increment()
Go automatically takes address of c when calling pointer method
4
c.Add(5)
Modifies the original struct via pointer receiver