gpt4 book ai didi

Go 中的指针和接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 01:40:41 29 4
gpt4 key购买 nike

我想了解我在这里做错了什么..感谢所有回复:)

如果取消注释“//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)
}

最佳答案

您包装到接口(interface)中的值不可寻址。该值必须可寻址才能调用指针接收器上的方法。 grow 方法是用指针接收器声明的。因此,编译器发现 plant 接口(interface)既不是由 plant1 类型实现的,也不是由 plant2 类型实现的。因此,您不能将 plant1plant2 作为 plant 传递给 showHeight 函数。并且切换是不可能的,因为 plant 接口(interface)的实现不包括 plant1plant2 类型。

参见 Why value stored in an interface is not addressable in Golang

关于Go 中的指针和接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53845785/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com