go - 从接口(interface)类型转换为实际类型的不可能的类型断言

标签 go

我有两个错误,

一个。不可能的类型断言。我们可以从接口(interface)类型转换为实际类型对象吗

不知道 evaluated but not used 是什么意思

type IAnimal interface {
    Speak()
}
type Cat struct{}

func (c *Cat) Speak() {
    fmt.Println("meow")
}



type IZoo interface {
    GetAnimal() IAnimal
}
type Zoo struct {
    animals []IAnimal
}
func (z *Zoo) GetAnimal() IAnimal {
    return z.animals[0]
}

测试

var zoo Zoo = Zoo{}

// add a cat
var cat IAnimal = &Cat{}
append(zoo.animals, cat) // error 1: append(zoo.animals, cat) evaluated but not used

// get the cat

var same_cat Cat = zoo.GetAnimal().(Cat) // error 2: impossible type assertions

fmt.Println(same_cat)

Playground

最佳答案

  1. 错误消息几乎说明了一切:

    tmp/sandbox129360726/main.go:42: impossible type assertion:
        Cat does not implement IAnimal (Speak method has pointer receiver)
    

    Cat 没有实现 IAnimal,因为 Speak(IAnimal 接口(interface)的一部分)有一个指针接收器,并且 Cat 不是指针。

    如果将 Cat 更改为 *Cat,它会起作用:

    var same_cat *Cat = zoo.GetAnimal().(*Cat)
    
  2. 错误几乎也说明了一切。

     append(zoo.animals, cat)
    

    您将 cat 附加到 zoo.animals(评估),然后丢弃结果,因为左侧没有任何内容。你可能想这样做:

    zoo.animals = append(zoo.animals, cat)
    

另一方面注意:当你直接赋值给一个变量时,不需要指定类型,因为 Go 可以为你确定它。因此

var same_cat Cat = zoo.GetAnimal().(Cat)

最好表达为:

var same_cat = zoo.GetAnimal().(Cat)

或者还有:

same_cat := zoo.GetAnimal().(Cat)

关于go - 从接口(interface)类型转换为实际类型的不可能的类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773848/

相关文章:

postgresql - 在postgres中将时间字段设置为当前时间

go - 如何创建 golang 网络套接字聊天?

c - 关于定义 : Rewriting Algorithm from Go Code to C

go - 如何在 Go 中编辑阅读器

go - 为什么两个goroutine的控制台输出看起来像同步

go - 如何处理 bytes.Buffer 流中的 io.EOF?

go - 富查询没有结果 - Hyeperledger Fabric v1.0

arrays - 迭代结构类型的数组

go - 使用ast获取一个函数中的所有函数调用

struct - 在 Go 中干净地实现结构的多级结构