【问题标题】:Type assertion errors when casting from interface to actual object从接口转换为实际对象时类型断言错误
【发布时间】:2017-08-02 04:30:00
【问题描述】:

在下面的示例中遇到类型断言错误。

错误:

49: 无法将 z(IZoo 类型)转换为 Zoo 类型:需要类型断言

49: 不能分配给 Zoo(z).animals

type IAnimal interface {}

type IZoo interface {}

type Zoo struct {
    animals map[string]IAnimal
}

func NewZoo() *Zoo {
    var z IZoo = &Zoo{}

    Zoo(z).animals = map[string]IAnimal{} // cannot convert z (type IZoo) to type Zoo: need type assertion
    
    return z // cannot use z (type IZoo) as type *Zoo in return argument: need type assertion
}

【问题讨论】:

    标签: go type-assertion


    【解决方案1】:

    错误消息说明了一切:您需要type assertion

    y := z.(Zoo)
    y.animals = map[string]IAnimal{}
    

    【讨论】:

    • 一行行不行吗,需要单独声明和赋值
    • @user2727195 z.(Zoo).animals = 你觉得这个表达式应该做什么?它的作用 - 它创建了一个临时对象,在此语句之后将被丢弃。因此,有一个问题:将值分配给您无法访问的对象字段意味着什么?您基本上可以删除该行,并且观察到的程序行为不会改变。
    • @zerkms 关于这个临时对象的文档有解释
    • 我不确定。这是一个通用知识 - Go 中的结构在分配时复制。
    • 澄清一下,Go 中的一切都是作业的副本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多