Duck typing
April 5, 2023
Interface types
An interface type defines a type set. A variable of interface type can store a value of any type that is in the type set of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is
nil
.InterfaceType = "interface" "{" { InterfaceElem ";" } "}" . InterfaceElem = MethodElem | TypeElem . MethodElem = MethodName Signature . MethodName = identifier . TypeElem = TypeTerm { "|" TypeTerm } . TypeTerm = Type | UnderlyingType . UnderlyingType = "~" Type .
The main thing to call out here is that in Go, interface implementations do not need to be explicitly declared, as they are in many other languages.
Any type that implements the method(s) defined in an interface automatically implement that interface.
This is often referred to as “Duck typing”. (If it walks like a duck…)
Let’s consider an exmaple:
type Greeter interface{
Greet() string
}
type Dog struct { /* .. maybe other fields ... */ }
// Greet implements the Greeter interface.
func (Dog) Greet() string {
return "Woof!"
}
type Fox struct { /* ... maybe other fields ... */ }
// Greet does not implement the Greeter interface, because
// there's no return value, because noone knows what the
// fox say.
func (Fox) Greet() {}
Quotes from The Go Programming Language Specification Version of December 15, 2022