'How to initialize a union of struct in cgo?

I have the below C struct defined in vehicles.h:

enum VehicleType {carType, bikeType};

struct Vehicle {
enum VehicleType vehicleType;
    union u {
        struct Car {
            char *brand;
        } car;
        struct Bike {
            double maxSpeed;
        } bike;
    } u;
};

In main.go I am trying to initialize some Vehicles:

// The below works fine
car := C.struct_Car{brand: C.CString("Ford")};
var vehicle1 C.struct_Vehicle;
vehicle1.vehicleType = C.carType;
carPtrUnion := (*C.struct_Car)(unsafe.Pointer(&vehicle1.u[0]))
*carPtrUnion = car

// This compiles but throws an error
bike := C.struct_Bike{maxSpeed: 150.0};
var vehicle2 C.struct_Vehicle;
vehicle2.vehicleType = C.bikeType;
bikePtrUnion := (*C.struct_Bike)(unsafe.Pointer(&vehicle2.u[0]))
*bikePtrUnion = bike

I get the following error at run time: panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4a8357] I think this is because &vehicle2.u[0] has index 0 so it will try to allocate to the Car while I have a Bike. How can I get around that ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source