duanmei2805 2018-02-03 23:50
浏览 210
已采纳

在GO中从一个结构复制到另一个结构

I have two structs:

type struct1 struct{
     arr [num1]byte
}

type struct2 struct{
     b1 [n1]uint64
     b2 [n2]uint64
     b3 [n3]uint64
}

Now, I have two pointers to these structs:

p1 := new(struct1);
p2 := new(struct2);

and after some computations, I want to copy p2 to a specified part of p1. Something like:

copy(p1.arr[k:], p2);

Where k is a positive integer. It can be easily done in C using memcpy, but I could not find an easy way to do it in GO without using any external libraries. Does anyone have any suggestions? I'll really appreciate it.

  • 写回答

2条回答 默认 最新

  • dou12352 2018-02-04 04:36
    关注

    You want to bypass the Go type system, which is unsafe. Therefore, you should be very careful. Implement this as a function and use the Go testing package to write tests. Check for errors. Write simple, readable code. Don't be clever.

    For example,

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    const num1 = 42
    
    type struct1 struct {
        arr [num1]byte
    }
    
    const (
        n1 = 1
        n2 = 2
        n3 = 1
    )
    
    type struct2 struct {
        b1 [n1]uint64
        b2 [n2]uint64
        b3 [n3]uint64
    }
    
    func arrInsert(p1 *struct1, i1 int, p2 *struct2) int {
        if p1 == nil || p2 == nil {
            return 0
        }
        if i1 < 0 || i1 >= len(p1.arr) {
            return 0
        }
        s1 := p1.arr[i1:]
        s2 := (*[unsafe.Sizeof(*p2)]byte)(unsafe.Pointer(p2))[:]
        return copy(s1, s2)
    }
    
    func main() {
        p1 := new(struct1)
        p2 := new(struct2)
        for i := range p2.b1 {
            p2.b1[i] = uint64(i + 10)
        }
        for i := range p2.b2 {
            p2.b2[i] = uint64(i + 20)
        }
        for i := range p2.b3 {
            p2.b3[i] = uint64(i + 30)
        }
        n := arrInsert(p1, 1, p2)
        fmt.Println(n)
        fmt.Println(*p1)
        fmt.Println((*[unsafe.Sizeof(*p2)]byte)(unsafe.Pointer(p2))[:])
        fmt.Println(*p2)
    }
    

    Playground: https://play.golang.org/p/KA0B0xpFR6l

    Output:

    32
    {[0 10 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]}
    [10 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 30 0 0 0 0 0 0 0]
    {[10] [20 21] [30]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器