在 go 中输入断言

Type assertion in go

我有这个代码片段:

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

我得到:

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

但是如果我修改为

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

它可以工作并打印对象的所有属性。我该如何转换它?

错误提示您要键入断言的类型是 *types.VirtualDisk 而不是 types.VirtualDisk

此外,您尝试使用的反射技巧完全没有必要,因为有一个 special form of the type assertion 报告断言是否成立。

看这个例子:

if disk, ok := device.(*types.VirtualDisk); ok {
    // Type assertion holds, disk is of type *types.VirtualDisk
    // You may use it so
}