在 Go 中,如何将结构转换为字节数组?

新手上路,请多包涵

我有一个我定义的结构实例,我想将它转换为一个字节数组。我试过 []byte(my_struct),但没有用。另外,我被指向了 binary package ,但我不确定我应该使用哪个功能以及我应该如何使用它。一个例子将不胜感激。

原文由 abw333 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 800
1 个回答

一种可能的解决方案是 "encoding/gob" 标准包。 gob 包创建了一个编码器/解码器,可以将任何结构编码为字节数组,然后将该数组解码回结构。 这里 有一篇很棒的帖子。

正如其他人所指出的那样,有必要使用这样的包,因为结构本质上具有未知的大小并且不能转换为字节数组。

我已经包含了一些代码和一个 play

 package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

type P struct {
    X, Y, Z int
    Name    string
}

type Q struct {
    X, Y *int32
    Name string
}

func main() {
    // Initialize the encoder and decoder.  Normally enc and dec would be
    // bound to network connections and the encoder and decoder would
    // run in different processes.
    var network bytes.Buffer        // Stand-in for a network connection
    enc := gob.NewEncoder(&network) // Will write to network.
    dec := gob.NewDecoder(&network) // Will read from network.
    // Encode (send) the value.
    err := enc.Encode(P{3, 4, 5, "Pythagoras"})
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // HERE ARE YOUR BYTES!!!!
    fmt.Println(network.Bytes())

    // Decode (receive) the value.
    var q Q
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
}

原文由 Adam 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题