指针&Go 中的接口 [英] Pointers & Interfaces in Go
问题描述
我试图了解我在这里做错了什么......感谢所有回复:)
I'm trying to understand what I'm doing wrong here.. all responses appreciated :)
如果取消注释//grow()"有效,
If uncomment "// grow()" works,
其他错误:
prog.go:38:2: 不可能类型 switch case:p(类型植物)不能有动态类型 plant1(grow 方法有指针接收器) prog.go:39:16:不可能的类型断言:植物 1 没有实现植物(生长方法有指针接收器) prog.go:40:2: 不可能的类型切换案例:p(类型植物)不能有动态类型植物2(生长方法有指针接收器) prog.go:41:16: 不可能的类型断言:plant2不实现植物(grow 方法有指针接收器)prog.go:60:12: 不能在参数中使用 p1(植物 1 类型)作为植物类型to showHeight: plant1 没有实现植物(grow 方法有指针接收器) prog.go:61:12: 不能使用 p2 (type plant2) 作为类型在 showHeight 的参数中种植植物:植物 2 不实现植物(grow 方法有指针接收器)
prog.go:38:2: impossible type switch case: p (type plant) cannot have dynamic type plant1 (grow method has pointer receiver) prog.go:39:16: impossible type assertion: plant1 does not implement plant (grow method has pointer receiver) prog.go:40:2: impossible type switch case: p (type plant) cannot have dynamic type plant2 (grow method has pointer receiver) prog.go:41:16: impossible type assertion: plant2 does not implement plant (grow method has pointer receiver) prog.go:60:12: cannot use p1 (type plant1) as type plant in argument to showHeight: plant1 does not implement plant (grow method has pointer receiver) prog.go:61:12: cannot use p2 (type plant2) as type plant in argument to showHeight: plant2 does not implement plant (grow method has pointer receiver)
https://play.golang.org/p/oMv7LdW85yK
package main
import (
"fmt"
)
type plant1 struct {
name string
height int
}
type plant2 struct {
species string
height int
}
func (self *plant1) grow() {
self.height++
}
func (self *plant2) grow() {
self.height++
}
func (self plant1) getHeight() int {
return self.height
}
func (self plant2) getHeight() int {
return self.height
}
type plant interface {
getHeight() int
//grow()
}
func showHeight(p plant) {
switch p.(type) {
case plant1:
fmt.Println(p.(plant1).name, `Height = `, p.(plant1).getHeight())
case plant2:
fmt.Println(p.(plant2).species, `Height = `, p.(plant2).getHeight())
}
}
func main() {
p1 := plant1{
name: `Plant 10`,
height: 1,
}
p2 := plant2{
species: `Plant 20`,
height: 1,
}
p1.grow()
p1.grow()
p2.grow()
showHeight(p1)
showHeight(p2)
}
推荐答案
您包装到接口中的值不可寻址.该值必须是可寻址的,以便在指针接收器上调用方法.grow
方法是用指针接收器声明的.所以编译器看到 plant
接口既不是由 plant1
类型实现的,也不是由 plant2
类型实现的.因此,您不能将 plant1
或 plant2
作为 plant
传递给 showHeight
func.并且切换是不可能的,因为 plant
接口的实现不包括 plant1
和 plant2
类型.
The value you wrap into interface isn't addressable. The value have to be addressable to call methods on pointer receivers. The grow
methods are declared with pointer receiver. So the compiler sees that plant
interface is being implemented neither by plant1
type nor by plant2
type. Thus you can't pass plant1
or plant2
as plant
to showHeight
func. And the switch is impossible because implementations of plant
interface don't include plant1
and plant2
types.
这篇关于指针&Go 中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!