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条)

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面