Reputation: 3270
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?
Upvotes: 3
Views: 75
Reputation: 166529
For a concise solution, which will be inlined, use methods.
For example,
package main
import "fmt"
type Vec3 struct {
X, Y, Z float64
}
func (v Vec3) Vector() Vector {
return Vector{v.X, v.Y, v.Z}
}
type Vector [3]float64
func (v Vector) Vec3() Vec3 {
return Vec3{X: v[0], Y: v[1], Z: v[2]}
}
func main() {
v3 := Vec3{X: 1, Y: 2, Z: 3}
v3v := v3.Vector()
fmt.Println(v3, v3v)
v := Vector{4, 5, 6}
vv3 := v.Vec3()
fmt.Println(v, vv3)
}
Output:
{1 2 3} [1 2 3]
[4 5 6] {4 5 6}
Upvotes: 3
Reputation: 1147
convert between arrays and structs without copying?
Nope.
What I intend to do is make supplying Vec3d instead of [3]float64 introduce no reduction in performance
Given that its impossible to convert arrays to structs without copying, I'd suggest to front-load your copying of type Vec3
-> [3]float64
at the start of the program so you won't experience any penalties during the main loop.
assign from one to the other without copying (or other slow overhead)
Consider completing the program first to see if performance is acceptable to the end-users.
In my experience working with 3d vectors, it's the application of 3d transforms on the vectors that's the real performance killer. Try running a profiler afterward to check which part of processing would produce the most bang for your development time.
Hope this helps. Cheers,
Upvotes: 2