Member-only story
Go for Developers: Errors, Interfaces and Methods
Introduction
In the previous part, we explored Defined Types, Pointers, and Functions. We learned how Go manages memory via Escape Analysis, how function values are represented as pointers to funcval structs, and how defined types provide zero-cost abstractions.
This article starts with Methods, building naturally on the Defined Types we just discussed, before moving on to Interfaces and Errors.
Methods
As we already know, Go does not have classes in the traditional Object-Oriented sense. Instead, behavior is attached to Defined Types using methods.
Syntax
Unlike languages where the current object is available inside a method as this or self without appearing in the function signature, Go requires the explicit declaration of the receiver's name and type in a special argument list between the func keyword and the method name.
// 1. A Defined Type
type Counter int
// 2. The Method
// (c Counter) is the receiver block: 'c' is the receiver variable, 'Counter' is the receiver type.
func (c Counter) Value() int {
return int(c)
}
// 3. Method with a pointer receiver
func (c *Counter) Increment() {
*c++
}