【问题标题】:Impossible type assertions with casting from interface type to the actual type从接口类型转换为实际类型的不可能的类型断言
【发布时间】:2017-03-13 21:35:48
【问题描述】:

我遇到了两个错误,

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

b.不知道评估但未使用是什么意思

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

【问题讨论】:

    标签: go


    【解决方案1】:
    1. 错误信息几乎说明了一切:

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

      Cat 没有实现IAnimal,因为SpeakIAnimal 接口的一部分)有一个指针接收器,而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)
    

    【讨论】:

    • 谢谢。对于错误 2,我改为更改方法签名,从说话中删除指针。 play.golang.org/p/1fQNj6rrsd这样的方法有可能吗
    • 当然,没有理由不能正常工作。:)
    • 抱歉没找到你,没用,play.golang.org/p/1fQNj6rrsd
    • var cat IAnimal = &Cat{} IAnimal 设置为指针,然后尝试将其声明为非指针。您需要始终保持一致。
    • 我明白了,所以如果我保存指针,我只能取回指针,我不能取回实际对象?
    猜你喜欢
    • 2017-08-02
    • 2014-01-08
    • 2012-12-26
    • 2023-04-03
    • 2020-04-06
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多