interface Animal作为数据类型构建的slice:
package main
import (
"fmt"
)
type Animal interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string
{
return "Woof!"
}
type Cat struct {}
//1func (c *Cat) Speak() string {
return "Meow!"
}
type Llama struct {}
func (l Llama) Speak() string
{
return "?????"
}
type JavaProgrammer struct {}
func (j JavaProgrammer) Speak() string {
return "Design patterns!"
}
func main() {
animals := []Animal{Dog{}, Cat{}, Llama{}, JavaProgrammer{}}
for _, animal := range animals {
fmt.Println(animal.Speak())
}
}
输出:
prog.go:33:32: cannot use Cat literal (type Cat) as type Animal in array or slice literal:
Cat does not implement Animal (Speak method has pointer receiver)
有疑问加站长微信联系(非本文作者)