Last active
February 3, 2026 20:25
-
-
Save dacr/644d689cc95e73892ed2f35f8f760bbb to your computer and use it in GitHub Desktop.
go interfaces / published by https://github.com/dacr/code-examples-manager #86809bee-7d41-4bca-ac58-78ac3ef26952/1bb6a6e1e944a86b1f1d80e3cb67dbac54ba36a2
This file contains hidden or 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
| /*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/ | |
| // summary : go interfaces | |
| // keywords : go, interfaces, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 86809bee-7d41-4bca-ac58-78ac3ef26952 | |
| // created-on : 2025-03-27T13:30:23+01:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : nix-shell -p go --run "go run $file" | |
| package main | |
| type Color string | |
| // ----------------------------------------------------------------------------------------- | |
| type Organism interface { | |
| Name() string | |
| } | |
| type Colored interface { | |
| Color() Color | |
| } | |
| type Creature interface { | |
| Organism | |
| Colored | |
| } | |
| // ----------------------------------------------------------------------------------------- | |
| type Fish struct { | |
| name string | |
| color Color | |
| weight int16 | |
| } | |
| type Bird struct { | |
| name string | |
| color Color | |
| weight int16 | |
| } | |
| // No need to use an implicit or extends keywords ! | |
| // ----------------------------------------------------------------------------------------- | |
| func (f Fish) Name() string { | |
| return f.name | |
| } | |
| func (f Fish) Color() Color { | |
| return f.color | |
| } | |
| func (b Bird) Name() string { | |
| return b.name | |
| } | |
| func (b Bird) Color() Color { | |
| return b.color | |
| } | |
| // ----------------------------------------------------------------------------------------- | |
| func main() { | |
| fish := Fish{"Goldfish", "Blue", 10} | |
| bird := Bird{"Parrot", "Green", 10} | |
| creatures := []Creature{fish, bird} | |
| organisms := creatures | |
| for _, creature := range creatures { | |
| println(creature.Name()) | |
| } | |
| for _, organism := range organisms { | |
| println(organism.Name()) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment