1 回答
TA贡献1846条经验 获得超7个赞
因为 a[]Person 不是a []Namer。让我们把你的例子更进一步:
type Namer interface {
Name() string
}
type Person struct {
name string
}
func (r Person) Name() string {
return r.name
}
type Thing struct {
name string
}
func (t Thing) Name() string {
return r.name
}
func Authors() []Namer {
authors := make([]Person, 10)
return authors
}
func main() {
namers := Authors()
// Great! This gives me a []Namer, according to the return type, I'll use it that way!
thing := Thing{}
namers := append(namers, thing)
// This *should* work, because it's supposed to be a []Namer, and Thing is a Namer.
// But you can't put a Thing in a []Person, because that's a concrete type.
}
如果代码期望收到 a []Namer,那就是它必须得到的。不[]ConcreteTypeThatImplementsNamer- 它们不可互换。
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报