Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 17

    Interfaces

    Interfaces define behavior contracts — a set of method signatures.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Interfaces define behavior contracts — a set of method signatures. Go interfaces are satisfied implicitly: no implements keyword. This enables decoupling, testability with mocks, and the accept-interfaces-return-structs API design principle.

    The empty interface any (Go 1.18+) accepts all types — use sparingly. Small interfaces (io.Reader, io.Writer with one method) are idiomatic. Understanding nil interface vs nil concrete value in interface is a classic interview trap.

    Interfaces power dependency injection, HTTP handlers, database drivers, and plugin architectures throughout the Go ecosystem.

    The story

    Google's internal RPC layers depend on small interfaces: an io.Reader for streaming uploads, a StorageBackend with Put and Get for swapping GCS mocks in tests. Uber's dependency injection wires concrete implementations behind interfaces so integration tests replace Kafka with an in-memory bus.

    Go interfaces are satisfied implicitly — no implements keyword — enabling decoupling without inheritance hierarchies that plague larger codebases.

    Understanding the topic

    Key concepts

    • type Reader interface { Read(p []byte) (n int, err error) }.
    • Implicit satisfaction — no declaration needed on implementing type.
    • Interface value holds (type, value) pair — nil interface vs typed nil.
    • Empty interface any — accepts everything; prefer generics or union constraints.
    • Type assertion: v := i.(ConcreteType) or v, ok := i.(ConcreteType).
    • Type switch on interface values for polymorphic dispatch.
    Visual overview
    io.Reader: Read(p []byte)
    *os.File
    implemented by
    *bytes.Buffer
    implemented by
    *strings.Reader
    implemented by

    Step-by-step explanation

    1. Define interface with method signatures.
    2. Concrete type implementing all methods satisfies interface automatically.
    3. Assign concrete to interface variable — dynamic dispatch at runtime.
    4. Interface with nil concrete value is not nil interface if type set.
    5. Compile-time check: var _ MyInterface = (*MyType)(nil).
    6. Embed interfaces in interfaces for composition.

    Practical code example

    Payment processor interface with mock implementation for testing:

    go
    package main
    import "fmt"
    type PaymentProcessor interface {
    Charge(amount float64, currency string) (string, error)
    }
    type StripeProcessor struct{}
    func (StripeProcessor) Charge(amount float64, currency string) (string, error) {
    return fmt.Sprintf("stripe_ch_%f_%s", amount, currency), nil
    }
    type MockProcessor struct{}
    func (MockProcessor) Charge(amount float64, currency string) (string, error) {
    return "mock_charge_id", nil
    }
    func checkout(processor PaymentProcessor, amount float64) {
    id, err := processor.Charge(amount, "USD")
    if err != nil {
    fmt.Println("failed:", err)
    return
    }
    fmt.Println("charged:", id)
    }
    func main() {
    checkout(StripeProcessor{}, 99.99)
    checkout(MockProcessor{}, 1.00)
    var _ PaymentProcessor = StripeProcessor{}
    }

    Output

    charged: stripe_ch_99.990000_USD
    charged: mock_charge_id

    Line-by-line code explanation

    • type PaymentProcessor interface { declares an interface. It requires one method, Charge, which takes an amount and a currency and returns a string ID and an error.
    • type StripeProcessor struct{} is a struct type with no fields. It only exists to carry methods.
    • func (StripeProcessor) Charge(amount float64, currency string) (string, error) { gives StripeProcessor a Charge method with the same signature as the interface. Go sees that and treats the type as a PaymentProcessor, with no implements keyword needed. The receiver has no name because the method never uses it.
    • return fmt.Sprintf("stripe_ch_%f_%s", amount, currency), nil builds a fake charge ID. The %f verb prints six decimal places, so 99.99 in USD becomes stripe_ch_99.990000_USD.
    • func (MockProcessor) Charge(amount float64, currency string) (string, error) { is a second implementation that ignores its arguments. It always returns the fixed ID mock_charge_id and a nil error.
    • func checkout(processor PaymentProcessor, amount float64) { accepts any value that has a Charge method. It does not know or care which concrete type it was given.
    • id, err := processor.Charge(amount, "USD") calls the method through the interface. If err is not nil, the function prints failed: and the error, then returns. Otherwise it prints charged: and the ID.
    • checkout(StripeProcessor{}, 99.99) passes the real processor, so it prints charged: stripe_ch_99.990000_USD. The next call, checkout(MockProcessor{}, 1.00), prints charged: mock_charge_id.
    • var _ PaymentProcessor = StripeProcessor{} is a compile-time check. The assignment only compiles if StripeProcessor really satisfies the interface, and the blank identifier discards the value.

    Key takeaway: var _ Interface = Type{} compile-time assertion. Small interfaces enable easy mocking. Accept PaymentProcessor interface in checkout function.

    Real-world use

    Where you'll use this in production

    • Repository interfaces for database swap in tests.
    • io.Reader/io.Writer streaming in HTTP and file processing.
    • http.Handler ServeHTTP for middleware chains.
    • Plugin systems loading implementations at runtime.

    Best practices

    • Keep interfaces small — 1-3 methods (interface segregation).
    • Define interfaces at consumer, not producer side.
    • Accept interfaces, return concrete types in public APIs.
    • Use compile-time assertion: var _ IF = (*T)(nil).
    • Avoid any — use generics or specific interfaces.
    • Document expected behavior and error semantics.

    Common mistakes

    • Returning nil concrete pointer in interface — not equal to nil interface.
    • Giant interfaces with 10+ methods — hard to mock and implement.
    • Defining interfaces before concrete types — consumer-driven interfaces.
    • Type assertion without ok — panics on wrong type.
    • Overusing any losing type safety.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionExplicit vs implicit interface satisfaction?+

    Answer

    Go implicit — type satisfies if it has all methods; no implements declaration.
    2BeginnerQuestionnil interface gotcha?+

    Answer

    Interface is nil only if both type and value nil; var p *T = nil; var i interface{} = p — i != nil.
    3IntermediateQuestionAccept interfaces return structs?+

    Answer

    Parameters as interfaces for flexibility; return concrete for callers to use full API.
    4IntermediateQuestionType assertion vs type switch?+

    Answer

    Assertion for single type; switch for multiple concrete types from one interface.
    5AdvancedQuestionDesign notification system with Email, SMS, Push — add Slack without caller change.+

    Answer

    Notifier interface with Send(); register implementations in slice; caller loops Notifiers — Open/Closed principle.

    Summary

    Interfaces define behavior; satisfaction is implicit. Small consumer-defined interfaces enable testing and decoupling. Beware nil interface vs typed nil pointer in interface. Type assertions and switches extract concrete types safely. Next lesson: pointers — explicit memory addresses.

    Ready to mark this lesson complete?Track your journey across the entire course.