Methods in Go
In Go, methods allow you to associate functions with specific data types. Most commonly, methods are attached to structs. This makes code more organized, readable, and closer to real-world modeling.
If structs represent data, methods represent behavior. Together, they form the backbone of Go applications.
What Is a Method?
A method is a function that has a receiver. The receiver tells Go which type the method belongs to.
Methods look similar to functions, but they are tied to a type.
Defining a Method
Let’s continue with a real-world example using a User struct.
type User struct {
ID int
Name string
Age int
}
Now, we define a method for this struct.
func (u User) greet() string {
return "Hello, my name is " + u.Name
}
Here:
u Useris the receiver- The method belongs to the
Usertype ubehaves like a variable inside the method
Calling a Method
Methods are called using the dot operator, just like accessing fields.
func main() {
user := User{ID: 1, Name: "Rahul", Age: 30}
message := user.greet()
fmt.Println(message)
}
This reads naturally and mirrors real-world behavior.
Methods vs Functions
Compare these two approaches:
- Function:
greet(user) - Method:
user.greet()
Methods improve readability and organization, especially in large codebases.
Methods with Pointer Receivers
If a method needs to modify the struct, you must use a pointer receiver.
func (u *User) birthday() {
u.Age += 1
}
This method increases the user’s age.
func main() {
user := User{Name: "Anita", Age: 25}
user.birthday()
fmt.Println(user.Age)
}
Go automatically handles pointer dereferencing, making method calls simple and safe.
Why Use Pointer Receivers?
- To modify struct fields
- To avoid copying large structs
- To improve performance
As a rule of thumb: if a method modifies data, use a pointer receiver.
Real-World Example: Product Pricing
Let’s model a product in an e-commerce system.
type Product struct {
Name string
Price float64
}
Now add methods to apply discounts.
func (p *Product) applyDiscount(percent float64) {
discount := p.Price * percent / 100
p.Price -= discount
}
func main() {
item := Product{Name: "Laptop", Price: 75000}
item.applyDiscount(10)
fmt.Println(item.Price)
}
This approach is widely used in real production systems.
Multiple Methods on the Same Struct
A struct can have many methods, each defining a different behavior.
func (p Product) isExpensive() bool {
return p.Price > 50000
}
Methods help keep related logic close to the data.
Best Practices for Methods
- Use methods to represent behavior
- Prefer pointer receivers for mutable data
- Keep method names meaningful and concise
- Group logic with the data it belongs to
What’s Next?
In the next lesson, you will learn about Interfaces in Go, which allow different types to share behavior without sharing implementation.