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

在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 MATLAB卫星二体模型仿真
  • ¥15 怎么让数码管亮的同时让led执行流水灯代码
  • ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
  • ¥85 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统