Last active
August 21, 2024 16:33
-
-
Save ccampo133/c87fa90fd72e486f2c7e463d37ef7b66 to your computer and use it in GitHub Desktop.
Duck Typing (horror) in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Duck interface { | |
Swim() | |
Quack() | |
} | |
type Mallard struct{} | |
func (m Mallard) Swim() { fmt.Println("mallard swimming") } | |
func (m Mallard) Quack() { fmt.Println("mallard quacking") } | |
type Dog struct{} | |
func (d Dog) Swim() { fmt.Println("dog swimming") } | |
func (d Dog) Bark() { fmt.Println("woof") } | |
func quack(ducks ...any) { | |
for _, duck := range ducks { | |
duck.(interface { Swim() }).Swim() | |
duck.(interface { Quack() }).Quack() | |
} | |
} | |
func main() { | |
quack(Mallard{}, Dog{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From https://www.ccampo.me/go/2024/08/20/go-duck-typing.html
Also https://go.dev/play/p/hi8vEivq29H