Implementing an interface
May 9, 2023
It feels like it’s been a month since we started on interfaces. Today we’re covering the final section on this topic!
Implementing an interface
A type
T
implements an interfaceI
if
T
is not an interface and is an element of the type set ofI
; orT
is an interface and the type set ofT
is a subset of the type set ofI
.A value of type
T
implements an interface ifT
implements the interface.
All three of these points should be pretty intuitive, especially if you’ve read the rest of the interface posts, but let’s give an example of each just to be sure.
-
T
is not an interface and is an element of the type set ofI
type Float interface { ~float32 | ~float64 } type myFloat float64 // myFloat implements Float; it is not // an interface, and it is an element // of the type set of Float. type Fooer interface { Foo() } type myFooer struct {} // myFooer implements Fooer; it is not // an interface, and it is an element // of the type set of Fooer by virtue of // the fact that it implements the Foo() // method func (f *myFooer) Foo() {}
-
T
is an interface and the type set ofT
is a subset of the typset ofI
type FooBarer interface { Foo() Bar() } var fb FooBarer var f Fooer = fb // FooBarer implements Fooer, because // it is an interface, and has a type set // that is a subset of FooBarer's type set.
-
A value of type
T
implements an interface ifT
implements the interface.This just extends the type implementation rules to values of that type.
Quotes from The Go Programming Language Specification Version of December 15, 2022