douzhan1238 2017-08-01 13:55
浏览 30
已采纳

在golang中转换重叠结构

I'm new to golang and trying to figure out the correct way of casting a block of bytes to the correct struct. All structs start with two bytes that dictate the layout of the remaining bytes. In C I would point to the beginning of the block of memory and cast it as a simple struct that only contained those two bytes (X below) but here I get an invalid type assertion. I'm probably way off base here any help you be appreciated.

package main

import (
    "fmt"
)

type A struct {
    tag   byte
    ver   byte
    data1 int
    data2 int
    data3 int
}

type B struct {
    tag   byte
    ver   byte
    data1 float32
}

type X struct {
    tag byte
    ver byte
}

func main() {
    var a A
    a.tag = 1
    a.ver = 1
    x := a.(X)

    fmt.Printf("%d,%d", x.tag, x.ver)
}

playground link

  • 写回答

2条回答 默认 最新

  • doupai5450 2017-08-01 14:10
    关注

    Here's my solution. It involves a few different tips:

    1. Embed the shared struct in the individual structs.
    2. Use encoding/binary package to load bytes into structs.
    3. Fill header struct with first two bytes, then make a decision on which subtype to make and fill.
    4. Always use fixed length int types for this kind of thing.
    5. Your field names must be UpperCase to be fillable from encoding/binary
    6. This is a pretty brittle way to manage marshalling.unmarshalling of data, but I'm sure you know that.

    Here's my solution:

    package main
    
    import (
        "bytes"
        "encoding/binary"
        "fmt"
        "log"
    )
    
    type A struct {
        X
        Data1 int32
        Data2 int32
        Data3 int32
    }
    
    type B struct {
        X
        Data1 int32
    }
    
    type X struct {
        Tag byte
        Ver byte
    }
    
    func main() {
        var err error
        data := []byte{1, 1, 0, 0, 0, 42}
        hdr := X{}
    
        err = binary.Read(bytes.NewReader(data[:2]), binary.BigEndian, &hdr)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(hdr.Tag, hdr.Ver)
    
        if hdr.Tag == 1 {
            b := B{}
            err = binary.Read(bytes.NewReader(data), binary.BigEndian, &b)
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(b.Data1)
        }
    
    }
    

    playground link

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

报告相同问题?

悬赏问题

  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出