【发布时间】:2020-01-25 07:35:08
【问题描述】:
当结构指针分配给接口时,为什么 Go 不认为是类型不匹配错误?
package main
import "fmt"
type ABC interface {
a() string
b() int
}
type XYZ struct {
aa string
bb int
}
func (xyz XYZ) a() string {
return "XYZ"
}
func (xyz XYZ) b() int {
return 123
}
func main() {
var xyz *XYZ
var abc ABC = xyz // type of abc is *main.XYZ,I think that Golang can find this error here, but why not?
fmt.Printf("%T\n", abc)
a, ret := abc.(*XYZ)
fmt.Println(a, ret) // type of a is *main.XYZ
fmt.Println(a.a()) // will occur a error, because the type of a(*main.XYZ) not implements the interface ABC
}
我想知道为什么 Go 不认为这是“var abc ABC = xyz”处的错误
【问题讨论】:
-
XYZ 很好地实现了接口 ABC,所以我想您可能误解了 Go 接口的工作原理?如果一个结构具有接口指定的所有方法,它会实现它而无需您对此做任何事情。这就是你所做的,XYZ拥有ABC指定的所有方法,即
a() string和b() int。 -
谢谢,我定义了a()和b()的接收者,是XYZ,不是*XYZ。 XYZ.a() 没问题,*XYZ.a() 不起作用。所以,我认为 *XYZ 没有实现 ABC。
标签: pointers go methods interface