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?
Go Binaries is an open-source server allowing non-Go users to quickly install tools written in Golang, without installing the Go compiler or a package manager — all you need is curl . Let's take a look at how it works, and how to use it!
Binary encoding uses the binary digit, or bit, as the fundamental unit of information, and a bit may only be a '0' or a '1' (only two possibilities since it is a binary-encoded system). By combining bits, numbers larger than 0 or 1 may be represented, and these bit collections are called words.
The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With