Created
January 15, 2022 08:10
-
-
Save percybolmer/866caa99af681d2099232119d9777f0c to your computer and use it in GitHub Desktop.
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
// Moveable is a interface that is used to handle many objects that are moveable | |
type Moveable interface { | |
Move(int) | |
} | |
// Person is a person, implements Moveable | |
type Person struct { | |
Name string | |
} | |
func (p Person) Move(meters int) { | |
fmt.Printf("%s moved %d meters\n", p.Name, meters) | |
} | |
// Car is a test struct for cars, implements Moveable | |
type Car struct { | |
Name string | |
} | |
func (c Car) Move(meters int) { | |
fmt.Printf("%s moved %d meters\n", c.Name, meters) | |
} | |
// Move is a generic function that takes in a Moveable and moves it | |
func Move[V Moveable](v V, meters int) { | |
v.Move(meters) | |
} | |
func main(){ | |
p := Person{Name: "John"} | |
c := Car{Name: "Ferrari"} | |
// Since the V paramter accepts Moveable, we can now call Move on Both Structs | |
Move(p, 10) | |
Move(c, 20) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment