Go by Example

Interfaces

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

An interface lists the methods a value must have to be used in a particular way. A method signature is its name and the types of its inputs and outputs. Go recognizes a type as satisfying an interface when it has those methods; no separate declaration is needed.

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 uses them. An interface with many methods is harder for other types to provide. A compile-time check can make Go report if a type no longer has every required method.

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