dongxing7530 2017-03-13 21:35
浏览 92
已采纳

从接口类型到实际类型的强制类型断言

I'm getting two errors,

a. Impossible Type assertion. Can we cast from interface type to the actual type object

b. not sure what's the meaning of 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]
}

Testing

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)

go Playground

  • 写回答

1条回答 默认 最新

  • dourui9570 2017-03-13 21:41
    关注
    1. The error message pretty much says it all:

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

      Cat does not implement IAnimal, because Speak (part of the IAnimal interface) has a pointer receiver, and Cat is not a pointer.

      If you change Cat to *Cat, it works:

      var same_cat *Cat = zoo.GetAnimal().(*Cat)
      
    2. The error pretty much says it all, too.

       append(zoo.animals, cat)
      

      You're appending cat to zoo.animals (evaluating), then throwing away the result, because there's nothing on the left side. You probably want to do this instead:

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

    One other side note: When you're assigning to a variable directly, there's no need to specify the type, because Go can determine it for you. Therefore

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

    would be better expressed as:

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

    or also:

    same_cat := zoo.GetAnimal().(Cat)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了