Structs and interfaces
Go composes with small interfaces and concrete data.
What you will be able to do
- Accept interfaces, return concrete types.
- Keep interfaces near the code that uses them.
- Embed to compose behaviour, not to build deep hierarchies.
In plain English
A struct stores data; an interface describes behaviour. Interfaces are satisfied implicitly, so define them where they are consumed, not where types are created. Prefer small interfaces with one or two methods.
type Lesson struct {
Slug string
Title string
}
type LessonStore interface {
Find(slug string) (Lesson, error)
}
type MemoryStore struct {
lessons map[string]Lesson
}
func (store MemoryStore) Find(slug string) (Lesson, error) {
lesson, ok := store.lessons[slug]
if !ok {
return Lesson{}, ErrNotFound
}
return lesson, nil
}Your turn
MediumImplement a store
Implement LessonStore with a MemoryStore that returns ErrNotFound for a missing slug.
GO · starter
func (store MemoryStore) Find(slug string) (Lesson, error) {
}Check your understanding before moving on.
Knowledge checkQuestion 1
How does a Go type satisfy an interface?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.