The Go language binary (gob) format is a self-described binary sequence. From its internal representation, the binary format of Go language consists of a sequence of 0 or more blocks, each of which contains a number of bytes, a sequence of 0 or more typeId-typeSpecification pairs, and a typeId-value pair.
If the typeId-value pair's typeId-value pair is predefined (for example, bool, int, string, etc.), these typeId-typeSpecification pairs can be omitted. Otherwise, use a type pair to describe a custom type (such as a custom structure). There is no difference between typeId between type pairs and value pairs.
As we will see, we can use the gob format without knowing its internal structure, because the encoding/gob package will handle all the underlying details for us behind the scenes.
The encoding/gob package in Go also provides the same encoding and decoding functions as the encoding/json package, and is easy to use. Generally speaking, if there is no requirement for naked eye readability, the gob format is the most convenient format for file storage and network transmission in Go.
Write Go language binary files
The following is a simple example to demonstrate how Go language generates a binary file, the code is as follows:
package main import ( "encoding/gob" "fmt" "os" ) func main() { info := "/golang/" file, err := ("./") if err != nil { ("File creation failed", ()) return } defer () encoder := (file) err = (info) if err != nil { ("Coding Error", ()) return } else { ("Coding successfully") } }
Running the above code will generate a file in the current directory, with the file contents as follows:
210c 001e 6874 7470 3a2f 2f63 2e62 6961
6e63 6865 6e67 2e6e 6574 2f67 6f6c 616e
672f
Read Go language binary files
Reading gob data is as simple as writing, the sample code is as follows:
package main import ( "encoding/gob" "fmt" "os" ) func main() { file, err := ("./") if err != nil { ("File opening failed", ()) return } defer () decoder := (file) info := "" err = (&info) if err != nil { ("Decoding failed", ()) } else { ("Decoding successfully") (info) } }
The operation results are as follows:
go run
Decoding successfully/golang/
This is the end of this article about reading and writing operations of Go binary files. For more information about reading and writing content of Go binary files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!