Go core
Browse topics

Interfaces and method sets

Version
1.27
Review
Draft

Summary#

A type implements a basic interface by having all of its methods. No declaration links the two. For a defined non-interface, non-pointer type T, its method set includes methods with receiver T. The method set of *T also includes methods with receiver *T. Embedding can promote additional methods.

Syntax#

go
type Speaker interface {
	Speak() string
}

var _ Speaker = (*Robot)(nil)

Example#

go
package main

import "fmt"

type speaker interface {
	speak() string
}

type dog struct{ name string }

func (d dog) speak() string { return d.name + " says woof" }

type robot struct{ beeps int }

func (r *robot) speak() string {
	r.beeps++
	return fmt.Sprintf("beep %d", r.beeps)
}

var _ speaker = (*robot)(nil) // checked by the compiler

func main() {
	unit := &robot{}
	for _, s := range []speaker{dog{name: "Rex"}, unit} {
		fmt.Println(s.speak())
	}
	fmt.Println(unit.beeps)

	_, ok := any(robot{}).(speaker)
	fmt.Println(ok)
}

Expected output#

Text
Rex says woof
beep 1
1
false

Common mistakes#

A method with a pointer receiver can be called on an addressable value because Go takes its address for the call. That shortcut does not change method sets, so a robot value cannot be assigned to speaker. Store &robot{} instead.

Version applicability#

Basic interfaces and method sets work this way from Go 1.0. The complete example requires Go 1.18 for any, an alias for interface{}.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0