为什么 Go 编译器不能推断出一个结构实现了一个接口
Why can't Go compiler deduce that a struct implements an interface
运行 下面的代码会导致编译错误:
cannot use authors (type []Person) as type []Namer in return argument
为什么Go编译不了?
type Namer interface {
Name() string
}
type Person struct {
name string
}
func (r Person) Name() string {
return r.name
}
func Authors() []Namer {
// One or the other is used - both are not good:
authors := make([]Person, 10)
var authors []Person
...
return authors
将 authors
声明为 authors := make([]Namer, 10)
或 var authors []Namer
会很好,但我不明白为什么编译器不能推断 Person
是 Namer
.
因为 []Person
不是 []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.
}
如果代码希望收到 []Namer
,那就是它 必须 得到的。不是 []ConcreteTypeThatImplementsNamer
- 它们不可互换。
运行 下面的代码会导致编译错误:
cannot use authors (type []Person) as type []Namer in return argument
为什么Go编译不了?
type Namer interface {
Name() string
}
type Person struct {
name string
}
func (r Person) Name() string {
return r.name
}
func Authors() []Namer {
// One or the other is used - both are not good:
authors := make([]Person, 10)
var authors []Person
...
return authors
将 authors
声明为 authors := make([]Namer, 10)
或 var authors []Namer
会很好,但我不明白为什么编译器不能推断 Person
是 Namer
.
因为 []Person
不是 []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.
}
如果代码希望收到 []Namer
,那就是它 必须 得到的。不是 []ConcreteTypeThatImplementsNamer
- 它们不可互换。