Skip to content

Interface declaration

An interface defines a set of method signatures. In Go, interfaces are satisfied implicitly – a type implements an interface if it provides all the methods declared in the interface. No explicit implements keyword is needed.

Define an interface Speaker and two structs that implement it.

package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string { return "Woof!" }
type Cat struct{}
func (c Cat) Speak() string { return "Meow!" }
func makeSound(s Speaker) {
fmt.Println(s.Speak())
}
func main() {
dog := Dog{}
cat := Cat{}
makeSound(dog)
makeSound(cat)
}
Terminal window
Woof!
Meow!