An interface in Go defines a behavior that a type must implement. Unlike other languages, Go does not use an `implements` keyword.
type Animal interface {
Speak() string
}
Learn how to use interfaces in Go to apply polymorphism.
An interface in Go defines a behavior that a type must implement. Unlike other languages, Go does not use an `implements` keyword.
type Animal interface {
Speak() string
}
interfaces.go
package main
import "fmt"
type Animal interface {
Speak() string
}
type Dog struct {}
type Cat struct {}
func (d Dog) Speak() string {
return "Woof!"
}
func (c Cat) Speak() string {
return "Meow!"
}
func MakeSound(a Animal) {
fmt.Println(a.Speak())
}
func main() {
dog := Dog{}
cat := Cat{}
MakeSound(dog)
MakeSound(cat)
}
Woof!
Meow!
🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊