Methods and Interfaces
Part of the Go course
The last lesson taught you how to bundle related fields into a struct, but a struct on its own only holds data, it has no behavior. If you want a Rectangle to know how to compute its own area, you either write a plain function that takes a Rectangle as an argument, or you attach the behavior to the type itself so it travels together with the data.
A method is an ordinary function with one extra ingredient: a receiver, a named variable of a specific type that sits in its own parentheses between the word func and the method's name. That receiver is what lets you write r.Area() instead of Area(r), the same way a remote control that has been paired to one specific television only ever controls that one television, no matter which button you press on it.
Want to learn Go Methods and Interfaces in a real environment?
Click below, get a fresh Linux box with Go ready to go, and work through Methods and Interfaces hands-on with an AI tutor that knows your code.
Start this lessonMethods and InterfacesWhat you'll learn
- Method declaration
- Receiver types
- Pointer vs value receivers
- Interface definition
- Implicit interface satisfaction
- Small interfaces
- Io.Writer example
Read this lesson in your language
All lessons in this course
20 lessons- 1Hello, Go25 min
- 2Variables and Types25 min
- 3Control Flow: if and for30 min
- 4Functions30 min
- 5Slices and Maps35 min
- 6Structs and Pointers35 min
- 7Methods and Interfaces35 min
- 8Error Handling35 min
- 9Modules and Project Structure35 min
- 10Tiny CLI Capstone40 min
- 11A Tour of the Standard Library40 min
- 12Testing and Benchmarks40 min
- 13Goroutines and Channels40 min
- 14Concurrency Patterns45 min
- 15Generics35 min
- 16HTTP Servers45 min
- 17Databases with database/sql45 min
- 18Performance and Profiling40 min
- 19Design Patterns in Go40 min
- 20Deployment and Production45 min
