I have a struct to represent a vector in 3D space.
type Vec3 struct {
X, Y, Z float64
}
Another library I am using does something similar, but different:
type Vector [3]float64
From my understanding, both types should occupy 24 bytes and each float64
in one type should line up with a float64
in the other type. So, we should be able to assign from one to the other without too much trouble. The compiler however does not like trying to cast these neither implicity nor explicitly, so the cleanest (but verbose) method appears to be to always construct the value manually:
// Vec3 to Vector
vec3 := Vec3{1, 2, 3}
vector := Vector{vec3.X, vec3.Y, vec3.Z}
// Vector to Vec3
vector := Vector{1, 2, 3}
vec3 := Vec3{vector[0], vector[1], vector[2]}
Another method I found is the following, but it looks no less verbose (and probably slower (and it won't stop us if one of the types ever changes)).
valueOfTargetType := *(*targetType)(unsafe.Pointer(&sourceValue))
So, can we cast these without explicitly constructing a new value?