Module 5 · Lesson 2 of 522/50 in the course~14 min
Module lessons (2/5)
Methods: receiver value vs pointer
Lesson preview5 hands-on exercises readyCourse Go · Module 5 — Structs and methods
func (p Persona) Hello() vs func (p *Persona) Rename(n string); when one, when the other.
What you'll learn in this lesson
- Define methods on struct types and custom types declared in the current package (
type Celsius float64). - Make an informed decision between value receiver
(t T)and pointer receiver(t *T). - Understand the automatic adjustment between
Tand*Ton calls and the danger of mixing both on the same type.
Overview
A method in Go is simply a function with a special additional argument called receiver, written between func and the method name.
In Go you can also attach methods to a type derived from int, float64, string or slice, as long as the new type is defined in your package:
Sections covered in this lesson
- 1Value receiver vs Pointer receiver
- 2When to choose a pointer receiver?
- 3Methods on any local named type
- 4Safe pointer receivers also on
nil - 5Method values as callbacks
- 6Guided practice
Pro Lesson · Module 5 — Structs and methods
Unlock "Methods: receiver value vs pointer" and the full Course Go curriculum
`func (p Persona) Hello()` vs `func (p *Persona) Rename(n string)`; when one, when the other.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.