go - 在 go 中输入断言

标签 go interface type-assertion

我有这段代码:

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
}

关于go - 在 go 中输入断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39791357/

相关文章:

go - 关于 Go 中的接口(interface)

java - 如何在Scala中实现扩展Comparable且没有特定类型的Java接口(interface)?

go - 如何将不同的值从 map[string]interface{} 转换为类型字符串

json - 可以使用 panic/recover 作为测试成功类型断言的方法吗?

go - 从接口(interface)转换为实际对象时出现类型断言错误

int64 中 []byte 的 Golang 大小

go - 在 channel 中使用引用是否错误/不好?

pointers - &deployment 如何满足 kubernetes 代码中的 runtime.Object 类型?

C# 接口(interface) - 用不同的签名实现

iPhone 应用程序转换为 iPad?