Go by Example

Interfaces

Go interfaces are satisfied implicitly - any type that implements the required methods satisfies the interface, no declaration needed.

An interface specifies a set of method signatures. A type satisfies it implicitly when it has those methods; it does not need to declare that relationship.

Dog satisfies Speaker because its Speak method matches the interface method signature.

package main
 
import "fmt"
 
type Speaker interface {
    Speak() string
}
 
type Dog struct{ Name string }
 
func (d Dog) Speak() string {
    return d.Name + " barks"
}
 
func announce(s Speaker) {
    fmt.Println(s.Speak())
}
 
func main() {
    announce(Dog{Name: "Milo"})
}

In production

Keep interfaces small and define them near the code that consumes them. A wide interface couples packages because every implementation must provide every method. Add a compile-time assignment such as var _ Speaker = Dog{} when you want the compiler to check that a type still satisfies an interface.

Enjoyed this? Get more software craft delivered to your inbox.