doutaoer3148 2018-10-23 15:54
浏览 25
已采纳

我们可以在数组和结构之间进行转换而无需“手动”构造吗?

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?

  • 写回答

2条回答 默认 最新

  • dongyi7901 2018-10-23 21:22
    关注

    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}
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部