6 Functions and methods

 

This chapter covers

  • When to use value or pointer receivers
  • When to use named result parameters and their potential side effects
  • Avoiding a common mistake while returning a nil receiver
  • Why using functions that accept a filename isn’t a best practice
  • Handling defer arguments

A function wraps a sequence of statements into a unit that can be called elsewhere. It can take some input(s) and produces some output(s). On the other hand, a method is a function attached to a given type. The attached type is called a receiver and can be a pointer or a value. We start this chapter by discussing how to choose one receiver type or the other, as this is usually a source of debate. Then we discuss named parameters, when to use them, and why they can sometimes lead to mistakes. We also discuss common mistakes when designing a function or returning specific values such as a nil receiver.

6.1 #42: Not knowing which type of receiver to use

Choosing a receiver type for a method isn’t always straightforward. When should we use value receivers? When should we use pointer receivers? In this section, we look at the conditions to make the right decision.

6.2 #43: Never using named result parameters

6.3 #44: Unintended side effects with named result parameters

6.4 #45: Returning a nil receiver

6.5 #46: Using a filename as a function input

6.6 #47: Ignoring how defer arguments and receivers are evaluated

6.6.1 Argument evaluation

6.6.2 Pointer and value receivers

Summary