Search code examples
gointerfacetype-assertion

Type assertion in go


I have this code snippet:

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

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


Solution

  • 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
    }