capypad
0 day streak
go / beginner
Snippet

Interfaces: Defining Behavior Contracts

Interfaces define a contract of methods that a type must implement. They enable polymorphism in Go, allowing different types to satisfy the same interface. When a type implements all methods in an interface, it implicitly satisfies that interface. Go is duck-typed, meaning you don't need to explicitly declare that a type implements an interface. This makes code flexible and testable. Empty interface (interface{}) can hold any value.

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
33
34
35
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("Dog says:", s.Speak())
 
s = Cat{}
fmt.Println("Cat says:", s.Speak())
 
// Using a slice of interfaces
speakers := []Speaker{Dog{}, Cat{}}
for _, speaker := range speakers {
fmt.Println("Animal says:", speaker.Speak())
}
}
Breakdown
1
type Speaker interface { Speak() string }
Defines an interface requiring a Speak() method returning a string
2
func (d Dog) Speak() string
Value receiver method - Dog type implements Speaker
3
var s Speaker
Declares a variable of interface type, initially nil
4
speakers := []Speaker{Dog{}, Cat{}}
Slice of interface type holding different concrete types