Module lessons (1/5)
Interfaces: define a behavior
An interface is a set of methods; whoever implements them satisfies it automatically (static duck typing).
What you'll learn in this lesson
- Define small, behavior-focused interfaces (
Greeter,io.Reader,io.Writer). - Understanding implicit satisfaction (static duck typing), without any keyword
implements. - Expect the method set rule between value receiver
Tand pointer receiver*Twhen assigning to an interface variable.
Overview
In Go an interface defines a method contract. Any type that implements those methods satisfies the interface automatically, without declaring implements or importing the package that defines the interface.
any (standard alias introduced in Go 1.18 for interface{}) does not require any methods and therefore can contain any value, but requires a type assertion or type switch before using the data:
Sections covered in this lesson
- 1Declaration and implicit satisfaction
- 2The empty interface
any(interface{}) - 3Method set: why
*T≠Tfor pointer receivers - 4Check on compilation:
var _ Interface = (*Type)(nil) - 5Guided practice
- 6Check for understanding
Unlock "Interfaces: define a behavior" and the full Course Go curriculum
An interface is a set of methods; whoever implements them satisfies it automatically (static duck typing).
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.