Methods and Receivers
Overview
Methods are functions with a receiver argument, allowing you to define behavior on types.
Method Syntax
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
rect := Rectangle{10, 5}
area := rect.Area() // 50Value vs Pointer Receivers
Value Receiver
func (r Rectangle) Scale(factor float64) Rectangle {
return Rectangle{r.Width * factor, r.Height * factor}
}
// Original unchanged
r := Rectangle{10, 5}
scaled := r.Scale(2) // New rectanglePointer Receiver
func (r *Rectangle) ScaleInPlace(factor float64) {
r.Width *= factor
r.Height *= factor
}
// Original modified
r := Rectangle{10, 5}
r.ScaleInPlace(2) // r is now {20, 10}When to Use Pointer Receivers
Use pointer receiver when: - Method needs to modify the receiver - Receiver is a large struct (avoid copying) - Consistency: if any method needs pointer, use pointer for all
type Buffer struct {
data []byte
}
func (b *Buffer) Write(p []byte) {
b.data = append(b.data, p...)
}
func (b *Buffer) String() string {
return string(b.data) // Even though it doesn't modify, use * for consistency
}Methods on Any Type
type MyInt int
func (m MyInt) Double() MyInt {
return m * 2
}
n := MyInt(5)
n.Double() // 10Automatic Dereferencing
Go automatically handles * and & for method calls:
r := Rectangle{10, 5}
(&r).ScaleInPlace(2) // Explicit pointer
r.ScaleInPlace(2) // Go handles it automatically
ptr := &Rectangle{10, 5}
(*ptr).Area() // Explicit dereference
ptr.Area() // Go handles it automaticallyEmbedding and Method Promotion
type Animal struct {
Name string
}
func (a Animal) Speak() string {
return "..."
}
type Dog struct {
Animal // Embedded
Breed string
}
d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
d.Speak() // Promoted method: "..."
d.Name // Promoted field: "Rex"Method Override
func (d Dog) Speak() string {
return "Woof!"
}
d.Speak() // "Woof!" (Dog's method)
d.Animal.Speak() // "..." (Animal's method)Summary
| Receiver | Use Case |
|---|---|
(t T) |
Read-only, small types |
(t *T) |
Modify state, large types |
| Feature | Description |
|---|---|
| Auto-deref | Go handles * and & |
| Embedding | Methods are promoted |
| Override | Inner type’s method shadows embedded |