capypad
0 day streak
go / beginner
Snippet

Interfaces and Polymorphism

Interfaces define behavior through method sets without implementing them. Types implicitly implement interfaces by providing all required methods. A variable of interface type can hold any value whose type satisfies the interface, enabling polymorphism.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main
import "fmt"
 
type Speaker interface {
Speak() string
}
 
type Dog struct{}
 
func (d Dog) Speak() string {
return "Woof!"
}
 
type Cat struct{}
 
func (c Cat) Speak() string {
return "Meow!"
}
 
func main() {
var s Speaker
s = Dog{}
fmt.Println(s.Speak())
s = Cat{}
fmt.Println(s.Speak())
animals := []Speaker{Dog{}, Cat{}}
for _, animal := range animals {
fmt.Printf("Says: %s\n", animal.Speak())
}
}
Breakdown
1
type Speaker interface { Speak() string }
Interface declares required method(s) without implementation
2
func (d Dog) Speak() string
Dog implicitly implements Speaker by providing Speak() method
3
var s Speaker
Interface variable can hold any concrete type that satisfies it
4
animals := []Speaker{Dog{}, Cat{}}
Slice of interface enables processing different types uniformly