Interfaces

View saved

Declare an interface

An interface lists method signatures. Any type with those methods implements it.

type Speaker interface {
	Speak() string
}

type Dog struct{}

func (Dog) Speak() string { return "woof" }

func say(s Speaker) {
	fmt.Println(s.Speak())
}

Use the empty interface carefully

any (alias for interface{}) accepts every value. Prefer concrete types or small interfaces.

var v any = "hello"
fmt.Println(v)

Type assert when needed

Pull a concrete type back out of an interface value.

var s Speaker = Dog{}
d, ok := s.(Dog)
fmt.Println(d, ok)

Interface tips

  • Accept interfaces, return concrete types when practical
  • Keep interfaces small—one or two methods
  • Standard library interfaces like io.Reader are good models
  • No implements keyword: satisfaction is implicit

Comments

One comment per signed-in account. Comments are saved with this page’s URL.