Created
March 28, 2025 09:02
-
-
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/5a003f867e21af6ce00a9cc04eb76b4d9ddded0b
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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// 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