2016-01-25 18:05:55 -08:00
|
|
|
// generics/dogsandrobots.go
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2016-01-25 18:05:55 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
|
|
|
|
type Dog struct {}
|
|
|
|
func (this Dog) speak() { fmt.Printf("Arf!\n")}
|
|
|
|
func (this Dog) sit() { fmt.Printf("Sitting\n")}
|
|
|
|
func (this Dog) reproduce() {}
|
|
|
|
|
|
|
|
type Robot struct {}
|
|
|
|
func (this Robot) speak() { fmt.Printf("Click!\n") }
|
|
|
|
func (this Robot) sit() { fmt.Printf("Clank!\n") }
|
|
|
|
func (this Robot) oilChange() {}
|
|
|
|
|
|
|
|
func perform(speaker interface { speak(); sit() }) {
|
|
|
|
speaker.speak();
|
|
|
|
speaker.sit();
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
perform(Dog{})
|
|
|
|
perform(Robot{})
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
Arf!
|
|
|
|
Sitting
|
|
|
|
Click!
|
|
|
|
Clank!
|
|
|
|
*/
|