让我们考虑以下程序
type Fruit interface {
Color() string
}
type Apple struct {
color string
}
func (x *Apple) Color() string {
return x.color
}
func (x *Apple) Compare(y Fruit) bool {
_, ok := y.(*Apple)
if ok {
ok = y.Color() == x.Color()
}
return ok
}
func main() {
a := Apple{"red"}
b := Apple{"green"}
a.Compare(&b)
}
现在,请注意最后一行 a.Compare(&b)
。这里我传递一个指向Apple
的指针。这正确工作,但请注意我的Compare
函数不接受指针(y Fruit)
。
现在,如果我将最后一行更改为 a.Compare(b)
,则会出现以下错误:
不能在 a.Compare 的参数中使用 b(Apple 类型)作为 Fruit 类型:
苹果没有实现Fruit(Color方法有指针接收器)
这里发生了什么?
最佳答案
出于 this answer 中概述的原因, Apple
没有实现 Fruit
,但 *Apple
实现了。如果您在 Apple
(而不是 *Apple
)上定义 Color
,则代码将编译:
package main
import (
"fmt"
)
type Fruit interface {
Color() string
}
type Apple struct {
color string
}
func (x Apple) Color() string {
return x.color
}
func (x Apple) Compare(y Fruit) bool {
_, ok := y.(Apple)
if ok {
ok = y.Color() == x.Color()
}
return ok
}
func main() {
a := Apple{"red"}
b := Apple{"green"}
fmt.Println(a.Compare(b))
}
关于go - 了解 Go 中接口(interface)和指针的类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570119/