Ready, Set, Go: Introduction to Methods

Hello, fellow coder! Brace yourself, for today we will explore Go programming with a focus on methods. Methods are akin to magic spells that allow us to perform various actions on custom data types. We'll delve into method definitions, method declarations, understand the function of receiver functions, and see them in practice. Exciting, right? Let's jump right in!

What's in a Method?

In Go, a method is a function attached to a specific type. Similar to how spells enable wizards to perform magical activities, methods allow us to conduct different operations on specific data types. Consider a racecar — it can accelerate, turn, brake, etc. A Go racecar type could have methods to define these actions.

Understanding the difference between methods and functions is vital. A function is a standalone entity, while a method always belongs to a type. Thus, a method is a special kind of function attached to a specific type.

Declaring Methods: The Articles of Incorporation

Declaring a method in Go follows this protocol:

func (receiver type) MethodName(parameters) (returnTypes) {
    // Code
}

Let's examine a Circle type:

type Circle struct {
   radius float64
}

// declaring a method on the Circle type 
func (c Circle) calculateArea() float64 {
   return 3.14 * c.radius * c.radius
}

In this example, we've declared a method calculateArea for the Circle type, which calculates the area when called in a Circle instance.

Unpacking the Receiver Function

Earlier, we emphasized the importance of receivers when declaring methods. A receiver is a specific type tied to every method. Go provides two types of receivers - a value receiver that takes a copy and a pointer receiver that uses a pointer.

// method with value receiver
func (c Circle) isLarge() bool {
   return c.radius > 10
}

// method with pointer receiver
func (c *Circle) doubleRadius() {
   c.radius *= 2
}

The isLarge method takes a value receiver (which does not modify the original), whereas the doubleRadius method uses a pointer receiver (which does modify the original).

With large structs, using value receivers in methods can potentially be inefficient because a lot of information will be copied each time the method is called.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal