doutaoer3148 2018-10-23 23: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-24 05: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条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制