Learn Go · 7/18

Interfaces: Programming by Contract

6 min read

Interfaces: Programming by Contract 📜

Welcome, Gopher! So, you've been cruising along, building things with structs and functions, and now you're hearing whispers of this mysterious "interface." Fear not! Interfaces are one of Go's most powerful and elegant features. They are the secret sauce to writing flexible, decoupled, and testable code.

Think of an interface as a contract. It outlines what a type must be able to do, without getting bogged down in the nitty-gritty of how it does it. This allows us to write functions that can work with any type, as long as it fulfills the contract. Let's dive in!


1. What is an Interface in Go?

Definition: An interface in Go is a type that defines a set of method signatures. It's like a blueprint for behavior. Any other type that has all the methods listed in the interface is said to "satisfy" or "implement" that interface.

The Problem: Imagine you're building a system to process payments. You might have different payment methods: CreditCard, PayPal, Bitcoin, etc. Each of these might have a Pay() method, but they would be implemented differently.

Without interfaces, you'd have to write a separate function to process each payment type: processCreditCardPayment(card CreditCard), processPayPalPayment(pp PayPal), and so on. This leads to a lot of duplicate code.

The Solution: An interface lets us define a common behavior. We can create a PaymentMethod interface that requires a Pay() method.

go
package main

import "fmt"

// PaymentMethod interface defines the contract
type PaymentMethod interface {
    Pay(amount float64) string
}

Now, we can write a single function that accepts any type that satisfies the PaymentMethod interface. This makes our code much cleaner and more flexible.


2. Implicit Implementation: Duck Typing 🦆

Here's where Go does something really cool and a bit different from many other languages. In Go, you don't need to explicitly say that a type implements an interface with a keyword like implements. If a type has all the methods declared in an interface, it automatically, or implicitly, satisfies that interface. This is often referred to as "duck typing": if it walks like a duck and quacks like a duck, then it must be a duck.

Let's see this in action with our payment example.

go
package main

import "fmt"

// The interface
type PaymentMethod interface {
    Pay(amount float64) string
}

// CreditCard type
type CreditCard struct {
    CardNumber string
}

// CreditCard implements the Pay method
func (cc CreditCard) Pay(amount float64) string {
    return fmt.Sprintf("Paid %.2f using Credit Card %s", amount, cc.CardNumber)
}

// PayPal type
type PayPal struct {
    Email string
}

// PayPal implements the Pay method
func (pp PayPal) Pay(amount float64) string {
    return fmt.Sprintf("Paid %.2f using PayPal account %s", amount, pp.Email)
}

// A function that accepts any PaymentMethod
func ProcessPayment(p PaymentMethod, amount float64) {
    fmt.Println(p.Pay(amount))
}

func main() {
    creditCard := CreditCard{CardNumber: "1234-5678-9876-5432"}
    payPal := PayPal{Email: "[email protected]"}

    ProcessPayment(creditCard, 25.50)
    ProcessPayment(payPal, 75.00)
}

What's happening here?

  • We defined a PaymentMethod interface with a Pay(amount float64) string method.
  • Both CreditCard and PayPal have a Pay method with the exact same signature.
  • Because they both have the required method, they both implicitly satisfy the PaymentMethod interface.
  • Our ProcessPayment function can now accept either a CreditCard or a PayPal value, because they both fulfill the contract.

Fun Fact: This implicit implementation makes Go interfaces very flexible. You can define an interface for types that were created in other packages, even ones you didn't write!


3. The Empty Interface (any) and Type Assertions 🤔

The What Now?: What if you have an interface with zero methods? This is called the empty interface, and in newer versions of Go (1.18+), it has a handy alias: any.

go
type Anything interface{}
// or, more commonly now:
type AlsoAnything any

Since the empty interface has no methods, every single type in Go satisfies it! This means you can use interface{} or any to hold a value of any type.

The Problem: This sounds great, but there's a catch. When you have a value of type any, you don't know what its underlying concrete type is. You can't just call methods on it or perform operations as if it were an int or a string.

go
func doSomething(i any) {
    // The following line would cause a compile error:
    // fmt.Println(i + 5) // Error: invalid operation: i + 5 (mismatched types any and int)
}

The Solution: Type Assertions

Go provides a mechanism called a type assertion to extract the underlying value of an interface. A type assertion takes an interface value and tries to assert that it is of a specific concrete type.

The syntax is i.(T), where i is the interface value and T is the type you're asserting.

go
package main

import "fmt"

func printValue(i any) {
    // Type assertion to get the underlying string value
    s, ok := i.(string)
    if ok {
        fmt.Printf("It's a string: %s\n", s)
        return
    }

    // Type assertion to get the underlying int value
    num, ok := i.(int)
    if ok {
        fmt.Printf("It's an integer: %d\n", num)
        return
    }

    fmt.Println("I don't know what this is!")
}

func main() {
    printValue("Hello, Gophers!")
    printValue(42)
    printValue(true)
}

In the example above, the value, ok := i.(Type) syntax is the safe way to do a type assertion. If the assertion is successful, ok will be true and value will hold the underlying value. If it fails, ok will be false and value will be the zero value for the type. This prevents your program from panicking if the type is not what you expect.

A cleaner way: The Type Switch

When you need to handle multiple possible types, a series of if/else statements can get clumsy. Go offers a type switch for this purpose.

go
package main

import "fmt"

func describe(i any) {
    switch v := i.(type) {
    case int:
        fmt.Printf("This is an integer: %d\n", v)
    case string:
        fmt.Printf("A string with the value: %s\n", v)
    case bool:
        fmt.Printf("A boolean: %t\n", v)
    default:
        fmt.Printf("Some other type I don't know: %T\n", v)
    }
}

func main() {
    describe(21)
    describe("hello")
    describe(true)
    describe(3.14)
}

4. Best Practices for Designing Interfaces 🛠️

  • Keep Interfaces Small: The Go proverb is "The bigger the interface, the weaker the abstraction." Smaller interfaces (often with just one method) are easier to satisfy and lead to more decoupled code. The io.Reader and io.Writer interfaces in the standard library are prime examples.
  • Interfaces Should Be Defined by the Consumer: In Go, it's common practice for the package that uses the interface to define it, not the package that implements it. This allows the consuming package to specify exactly what it needs without creating unnecessary dependencies.
  • Use Descriptive Names: For single-method interfaces, it's a common convention to name them by adding "er" to the method name, e.g., Reader, Writer, Stringer.
  • Use any Sparingly: While the empty interface is powerful, it bypasses Go's static type safety. Only use it when you truly need to work with values of unknown types. Prefer specific interfaces whenever possible.

Further Reading 📚

Challenge

Challenge: Build a Polymorphic Data Processing Pipeline

You are tasked with building a flexible data processing pipeline in Go. The system must be able to ingest data from various sources and process it to generate a summary report. The key requirement is that the system should be easily extendable with new data sources and new data types without modifying the core pipeline logic.

Your tasks are to:

  1. Define a DataSource interface with one method: FetchData() ([]any, error).
  2. Create two concrete types that implement the DataSource interface:
    • DatabaseSource: A struct that holds a slice of any and returns it in its FetchData method, simulating reading from a database.
    • APISource: A struct that, in its FetchData method, returns a hardcoded slice of any, simulating a call to an external API.
  3. Define a ReportGenerator interface with one method: Generate(items []any) (string, error).
  4. Create a concrete type SummaryReport that implements the ReportGenerator interface. The Generate method should iterate over the input slice. Using a type switch, it must count the number of User structs, Transaction structs, and unrecognized types. It should then return a formatted summary string.
  5. Implement a function RunPipeline(source DataSource, generator ReportGenerator) that fetches data from the source and passes it to the generator to produce a report. This function should not be aware of the concrete types of its arguments.
  6. In the main function, initialize your data sources with sample data (instances of User and Transaction structs, and perhaps a primitive type like a string to test the 'unrecognized' case). Then, instantiate the SummaryReport generator and use RunPipeline to process data from both DatabaseSource and APISource.

Expected result

Your final code should be a complete, runnable Go program that correctly defines and implements all the specified interfaces and structs.

Specifically, your solution must contain:

  1. An interface named DataSource with the method FetchData() ([]any, error).
  2. A struct named DatabaseSource that satisfies the DataSource interface.
  3. A struct named APISource that satisfies the DataSource interface.
  4. An interface named ReportGenerator with the method Generate(items []any) (string, error).
  5. A struct named SummaryReport that satisfies the ReportGenerator interface. Its Generate method must use a type switch to correctly differentiate and count User structs, Transaction structs, and any other types passed to it.
  6. A function RunPipeline(source DataSource, generator ReportGenerator) that correctly calls the methods on the provided interfaces and handles potential errors.
  7. The main function should be fully implemented to demonstrate the pipeline's functionality by processing data from both an APISource and a DatabaseSource instance and printing the generated summary reports.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.