-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterfaces.go
More file actions
48 lines (35 loc) · 761 Bytes
/
interfaces.go
File metadata and controls
48 lines (35 loc) · 761 Bytes
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
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import "fmt"
// Define an interface
type Speaker interface {
Speak() string
hear() string
}
// Implement the interface for a type
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
func (d Dog) hear() string {
return "NothingDog!"
}
type Cat struct{}
func (c Cat) Speak() string {
return "Meow!"
}
func (c Cat) hear() string {
return "NothingCat!"
}
// Use the interface in a function
func LetItSpeak(speaker Speaker) {
fmt.Println(speaker.Speak())
fmt.Println(speaker.hear())
}
func main() {
// Create an instance of the Dog type
myDog := Dog{}
myCat := Cat{}
// Pass the Dog instance to the function that expects a Speaker interface
LetItSpeak(myDog) // Output: woof!
LetItSpeak(myCat) // Output: Meow!
}