Methods in Go
In Go, methods are a special type of function associated with a specific type, often termed as a "receiver". These methods allow us to define behaviors for different types and enable us to apply the principles of object-oriented programming (OOP). In this article, we'll learn about methods in Go and how we can use them to enhance our Go programming skills.
Defining Methods in Go
Unlike other object-oriented languages, Go doesn't have classes to define methods. Instead, methods in Go are defined on types. Let's start off with a simple example:
type Rectangle struct {
Length float64
Breadth float64
}
func (r Rectangle) Area() float64 {
return r.Length * r.Breadth
}
Here Rectangle
is a struct type and Area
is a method with Rectangle
as the receiver type. The Area
method calculates the area of a rectangle.
Calling Methods in Go
Methods can be called similar to how we call functions. Access the method using the dot (.
) operator.
func main() {
r := Rectangle{10.5, 20.0}
fmt.Println("Area of rectangle r:", r.Area())
}
Pointer Receivers vs Value Receivers
There are two types of receivers in Go: value receivers and pointer receivers.
Value receivers in Go create a copy of the receiver value and use this copy to perform the method actions. Here is an example:
func (r Rectangle) Area() float64 {
return r.Length * r.Breadth
}
Pointer receivers, on the other hand, do not create a copy, and instead use a reference to the original type to perform actions. This means any changes made inside the method will affect the original value. Here is an example:
func (r *Rectangle) Area() float64 {
r.Length = r.Length * 2
return r.Length * r.Breadth
}
Choosing Between Pointer and Value Receivers
There are a few guidelines that can help you decide when to use a pointer receiver and when to use a value receiver:
- If you want to change the receiver value within your method (as it happens in the example with the
Area
method), you should use a pointer receiver. - If your receiver is a large struct, a pointer receiver will be more memory-efficient.
- If your receiver is a simple, basic type like int or bool, use a value receiver, it will be more straightforward.
Conclusion
Methods in Go provide a way to define behavior for specific types and enable us to program in an object-oriented style. Go's approach to methods offers both the flexibility of functions with the capability to create methods for user-defined types.
Mastering methods will allow you to write more efficient and modular code. Keep practicing and exploring more with different receiver types and methods to get a better understanding.