I got the runtime error message 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)
}
I wish to use the endian auto convert function, how could I do? By the way, is there more efficient way?
Use exported fixed size fields. For example,
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)
}
Output:
t1: {[97 98 99 100 101] 1234}
t2: {[97 98 99 100 101] 1234}
Quoting exactomundo from binary/encoding docs:
A fixed-size value is either a fixed-size arithmetic type (int8, uint8, int16, float32, complex64, ...) or an array or struct containing only fixed-size values.
And therefore:
type T1 struct {
f1 [5]uint8
f2 int32
}
works here.