go - 在 Go 中使用编码/二进制进行字节字节序转换

标签 go

我收到运行时错误消息Write T1 binary.Read: invalid type main.T1

package main

import (
    "encoding/binary"
    "net"
)

type T1 struct {
    f1 [5]byte
    f2 int
}

func main() {
    conn, _ := net.Dial("tcp", ":12345")
    l1 := T1{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
    binary.Write(conn, binary.BigEndian, &l1)
}

我想使用字节序自动转换功能,怎么办? 请问有没有更高效的方法?

最佳答案

使用导出的固定大小字段。例如,

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type T struct {
    F1 [5]byte
    F2 int32
}

func main() {
    var t1, t2 T
    t1 = T{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
    fmt.Println("t1:", t1)
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, &t1)
    if err != nil {
        fmt.Println(err)
    }
    err = binary.Read(buf, binary.BigEndian, &t2)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("t2:", t2)
}

输出:

t1: {[97 98 99 100 101] 1234}
t2: {[97 98 99 100 101] 1234}

关于go - 在 Go 中使用编码/二进制进行字节字节序转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8039552/

相关文章:

python - Google App Engine 上的 Golang App 调用 Python 脚本

go - Golang MySQL驱动程序不允许使用ProxySQL进行数据库更改

http - 在超时处理程序中进入竞争条件

go - 为什么 "switch t := policy.Parameter.(type)"不适用于 viper.Unmarshal()

mongodb - mgo 将 mapreduce 转换为聚合命令

go - 如何使用反射更改结构片段的字段?

戈朗 : Wait x amount of time before looping again without starting new goroutine

go - `go get cloud.google.com/go/cloudtasks/apiv2`的一些问题;未定义: grpc. RoundRobin

go - 如何在数组列表中保存[] byte数据

json - JSON解析异常