Go Tutorial: Methods
Attach behaviour to your types. Instead of functions that take a struct, write functions that belong to one.
Functions that belong to a type
You know how to write a function. You know how to define a struct.
A method is the combination: a function that is attached to a specific type. Instead of writing `printPerson(p)` you write `p.Print()`. Instead of `calculateArea(r)` you write `r.Area()`.
The code is the same. But the organisation is completely different — and far more readable as your programs grow.
Every real Go codebase is built on methods. Thirteen steps.
What you'll learn in this Go methods tutorial
This interactive Go tutorial has 10 hands-on exercises. Estimated time: 22 minutes.
- What is a method — Think of a method as a behaviour that belongs to a specific type. A `Book` can `Describe()`. A `Member` can `Greet()`.\n…
- Define a method — Write your own method. Add a `Describe()` method to `Book` that prints: `"The Great Gatsby by F. Scott Fitzgerald (1925)…
- ahha — value receiver cannot change the original — A value receiver receives a copy. Changes inside the method don't affect the original.\nRun this. Notice that calling `t…
- Pointer receiver — actually changes the struct — To modify the original struct from a method, use a pointer receiver: `(b *Book)`.\nNow the method receives the address —…
- Value vs pointer receiver — side by side — Rule of thumb: reading only? Use a value receiver. Mutating the struct? Use a pointer receiver. Large struct? Use a poin…
- Methods with parameters and return values — Methods accept parameters and return values just like regular functions.\nAdd an `IsAvailable() bool` method that return…
- Methods on non-struct types — You can add methods to any named type — not just structs.\n`type ISBN string` is a named type based on `string`. You can…
- String() — fmt prints it automatically — If you add a `String() string` method to your type, `fmt.Println` calls it automatically.\nThis is Go's way of letting y…
- Fix the broken method — The `ReturnBook` method below is supposed to mark a book as returned and clear who checked it out. But it does not work …
- Build a library system — No starter code. Build two types with methods:\n**Book** (Title, Author, IsCheckedOut bool) — CheckOut(), Return(), Desc…
Go Methods concepts covered
- Functions that belong to a type