Go Foundations·Clarity, then concurrency

Structs and interfaces

Go composes with small interfaces and concrete data.

Beginner 14 min read Lesson 8 of 300 Challenge included
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.

store.goGo
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

Implement a store

Medium

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Goroutines and channels
Lesson 8 of 300 · 0% of course