Interfaces
An interface is a checklist of skills.
It lists method names and shapes.
Any type that has those methods fits the interface automatically.
There is no implements keyword. If you have the skills, you pass.
Defining an interface
Write type Name interface { ... }.
List the methods a type must have.
Keep the checklist small when you can.
Satisfying an interface
If a type has the right methods, you can put it in an interface variable.
Then you call those methods through the interface.
Different types can share the same checklist.
Empty interface and any
interface{} can hold a value of any type.
Since Go 1.18 you can also write any.
Use it carefully. Smaller checklists with real skills are usually clearer.
Type assertions
When you have an interface value, you may need the real type back.
Assert carefully. Prefer the two-value form so you can check ok.
Type switches
A type switch asks: what real type is inside?
Each case handles one type.
Small interfaces (often one method) fit Go well. Look at io.Reader and error.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.