go / beginner
Snippet
Methods and Value vs Pointer Receivers
Go does not have classes, but you can define methods on types. A method has a receiver parameter between func and the method name. Value receivers (r Rectangle) receive a copy, while pointer receivers (r *Rectangle) receive a pointer to the original. Use pointer receivers when you need to modify the receiver or when the struct is large (avoiding copies). Conventionally, if any method on a type has a pointer receiver, all methods should too.
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package mainimport "fmt"type Counter struct {value int}func (c Counter) GetValue() int {return c.value}func (c *Counter) Increment() {c.value++}func (c *Counter) Add(v int) {c.value += v}type Rectangle struct {Width, Height int}func (r Rectangle) Area() int {return r.Width * r.Height}func (r *Rectangle) Scale(factor int) {r.Width *= factorr.Height *= factor}func main() {c := Counter{value: 10}fmt.Println("Initial:", c.GetValue())c.Increment()fmt.Println("After increment:", c.value)c.Add(5)fmt.Println("After adding 5:", c.value)rect := Rectangle{Width: 5, Height: 3}fmt.Printf("Area: %d\n", rect.Area())rect.Scale(2)fmt.Printf("Scaled area: %d (Width: %d, Height: %d)\n",rect.Area(), rect.Width, rect.Height)}
Breakdown
1
func (c Counter) GetValue() int
Value receiver - receives a copy of Counter. Safe but cannot modify original.
2
func (c *Counter) Increment()
Pointer receiver - can modify c.value. Go automatically handles & and *.
3
rect.Area()
Value receiver works on value types; rect is copied for the method call
4
rect.Scale(2)
Pointer receiver modifies the original; Go automatically passes &rect