Thuta Learning
IntermediateProgrammingbeginner

Interfaces

Relax. We'll talk through this in plain words — no textbook voice.

Interface is a contract that defines method behavior. In Go, you don't need to explicitly write "implements" for an interface. If a type has all the methods in the interface, it automatically satisfies it.

go
package main

import "fmt"

type Notifier interface {
    Notify(message string)
}

type EmailNotifier struct{}

func (EmailNotifier) Notify(message string) {
    fmt.Println("Email:", message)
}

func sendAlert(n Notifier) {
    n.Notify("Server is running")
}

func main() {
    email := EmailNotifier{}
    sendAlert(email)
}

EmailNotifier has a Notify method, so it satisfies the Notifier interface. That's why sendAlert can accept an EmailNotifier.

You should see
Email: Server is running

Info

Using interfaces lets a function work with several types that share the same behavior, instead of being tied to one specific concrete type.

Easy traps

  • If the method signature doesn't exactly match what the interface expects, it won't satisfy it. The parameter types, return type, and method name all need to match exactly.