52 lines
994 B
Go
Raw Normal View History

2015-11-03 12:00:44 -08:00
// staticchecking/petspeak.go
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -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.
2015-11-03 12:00:44 -08:00
package main
import "fmt"
type Cat struct {}
func (this Cat) speak() { fmt.Printf("meow!\n")}
type Dog struct {}
func (this Dog) speak() { fmt.Printf("woof!\n")}
type Bob struct {}
2016-01-25 18:05:55 -08:00
func (this Bob) bow() {
fmt.Printf("thank you, thank you!\n")
}
func (this Bob) speak() {
fmt.Printf("Welcome to the neighborhood!\n")
}
func (this Bob) drive() {
fmt.Printf("beep, beep!\n")
}
2015-11-03 12:00:44 -08:00
type Speaker interface {
speak()
}
func command(s Speaker) { s.speak() }
2016-01-25 18:05:55 -08:00
// If "Speaker" is never used
// anywhere else, it can be anonymous:
2015-11-03 12:00:44 -08:00
func command2(s interface { speak() }) { s.speak() }
func main() {
command(Cat{})
command(Dog{})
command(Bob{})
command2(Cat{})
command2(Dog{})
command2(Bob{})
}
2016-01-25 18:05:55 -08:00
/* Output:
meow!
woof!
Welcome to the neighborhood!
meow!
woof!
Welcome to the neighborhood!
*/