go / intermediate
Snippet
Implicit Interface Implementation
In Go, interfaces are implemented implicitly. A type satisfies an interface by simply implementing its methods; there is no 'implements' keyword. This decouples the definition of the interface from its implementation.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package mainimport "fmt"type Describer interface {Describe() string}type Product struct {Name stringPrice float64}func (p Product) Describe() string {return fmt.Sprintf("%s costs $%.2f", p.Name, p.Price)}func main() {var d Describer = Product{Name: "Keyboard", Price: 49.99}fmt.Println(d.Describe())}
Breakdown
1
type Describer interface { ... }
Defines an interface with a Describe method that returns a string.
2
func (p Product) Describe() string
The Product struct implements the Describe method, satisfying the Describer interface.
3
var d Describer = Product{...}
A Product instance can be assigned to a Describer variable because it satisfies the interface.