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 13 hands-on exercises. Estimated time: 22 minutes.
- What is a method — A method is just a function with one extra thing: a receiver.
- Define a method — Write your own method.
- Value receiver — reads but does not change — A value receiver receives a copy of the struct. Changes inside the method do not affect the original.
- Pointer receiver — actually changes the struct — To modify the original struct from a method, use a pointer receiver: `(p *Person)`.
- Value vs pointer receiver — side by side — Rule of thumb:
- Methods with parameters — Methods can accept parameters just like regular functions.
- Methods with return values — Methods return values the same way functions do.
- Multiple methods on one type — A type can have as many methods as you need. They all live separately in code but belong to the same type.
- Return self for sequential calls — Go does not have built-in method chaining. But if your method returns a pointer to the same type, you can call multiple …
- Methods on non-struct types — You can add methods to any named type — not just structs.
- String() — fmt prints it automatically — If you add a `String() string` method to your type, `fmt.Println` will call it automatically.
- Fix the broken method — The `Restock` method below is supposed to add items to a product's stock. But it does not work — the stock stays at 10 a…
- Build a shape calculator — No starter code.
Go Methods concepts covered
- Functions that belong to a type