duanmeng3573 2016-09-30 12:17
浏览 74
已采纳

在go中输入断言

I have this code snippet:

if (reflect.TypeOf(device).String() == "*types.VirtualDisk") {
    disk := device.(types.VirtualDisk)
    fmt.Printf("%v - %v 
", "capacityInKB", disk.CapacityInKB)
}

to which I get:

impossible type assertion: types.VirtualDisk does not implement types.BaseVirtualDevice (GetVirtualDevice method has pointer receiver)

But If I modify it to

if (reflect.TypeOf(device).String() == "*types.VirtualDisk") {
    //disk := device.(types.VirtualDisk)
    fmt.Printf("%v - %v 
", "capacityInKB", device)//disk.CapacityInKB)
}

It works and prints all the properties of the object. How am I suppose to convert this?

  • 写回答

1条回答 默认 最新

  • duanleiliu7373 2016-09-30 12:23
    关注

    The error hints that the type you want to type assert is *types.VirtualDisk and not types.VirtualDisk.

    Also that reflection trick you're trying to do is completely unnecessary, as there is a special form of the type assertion which reports whether the assertion holds.

    See this example:

    if disk, ok := device.(*types.VirtualDisk); ok {
        // Type assertion holds, disk is of type *types.VirtualDisk
        // You may use it so
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 STM32阿里云平台显示不了传感器采集的数据
  • ¥20 三菱FX系列PLC上位机串口下指令置位M64和M65,这两条指令分别是什么呢?
  • ¥15 有关结冰模拟程序咨询