Go — Methods
Value receivers
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) String() string {
return fmt.Sprintf("Rectangle(%.1f x %.1f)", r.Width, r.Height)
}
func main() {
r := Rectangle{Width: 5, Height: 3}
fmt.Println(r.Area())
fmt.Println(r)
}
Pointer receivers
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
func (r *Rectangle) SetWidth(w float64) {
r.Width = w
}
func main() {
r := Rectangle{Width: 5, Height: 3}
r.Scale(2)
fmt.Println(r.Area()) // 30
}
When to use pointer receivers
- Method modifies the receiver
- Method is expensive to copy (large struct)
- Consistency — if any method needs pointer, use pointer for all
Interface implementation
type Stringer interface {
String() string
}
// Rectangle implements Stringer via String() method
func (r Rectangle) String() string {
return fmt.Sprintf("Rectangle(%.1f x %.1f)", r.Width, r.Height)
}
Method embedding
type Point struct{ X, Y float64 }
func (p Point) Distance(q Point) float64 {
dx := p.X - q.X
dy := p.Y - q.Y
return math.Sqrt(dx*dx + dy*dy)
}
type Circle struct {
Center Point
Radius float64
}
func main() {
c := Circle{Center: Point{0, 0}, Radius: 5}
fmt.Println(c.Center.Distance(Point{3, 4}))
}
Mini Practice
Write Go code that:
- Creates a struct with value and pointer receiver methods
- Implements the
Stringerinterface - Uses method embedding
- Shows when to use pointer vs value receivers
Up Next
In the next lesson, you'll learn about Interfaces — Go's implicit interfaces.
Related Topics
Frequently Asked Questions about Methods
What is Methods in Go?
Methods is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Methods?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Methods.
Why is Methods important in Go?
Methods is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.