Golang : Saving(serializing) and reading file with GOB
Golang has a package ( GOB ) that allows developers to store memory values( such as int[], float64[] or any kind of structs ) into files for storage, store in a database, transmit over a network or processing the data with another program. Saving memory values to file is also known as serializing Golang objects. In this tutorial, we will learn how to serialize int[]
values to a file in a program and retrieve the int[]
values from another program.
savefilegob.go
package main
import (
"encoding/gob"
"fmt"
"os"
)
func main() {
data := []int{101, 102, 103}
// create a file
dataFile, err := os.Create("integerdata.gob")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// serialize the data
dataEncoder := gob.NewEncoder(dataFile)
dataEncoder.Encode(data)
dataFile.Close()
}
and retrieve the serialized objects or values:
readfilegob.go
package main
import (
"encoding/gob"
"fmt"
"os"
)
func main() {
var data []int
// open data file
dataFile, err := os.Open("integerdata.gob")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
dataDecoder := gob.NewDecoder(dataFile)
err = dataDecoder.Decode(&data)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
dataFile.Close()
fmt.Println(data)
}
Output :
[101 102 103]
References :
http://golang.org/pkg/encoding/gob/
https://socketloop.com/references/golang-encoding-gob-encoder-encode-function-example
https://www.socketloop.com/references/golang-encoding-gob-newencoder-function-examples
See also : Golang : Tutorial on loading GOB and PEM files
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.6k Golang : How to solve "too many .rsrc sections" error?
+11.2k Golang : Find age or leap age from date of birth example
+7.5k Golang : Test if an input is an Armstrong number example
+14.8k JavaScript/JQuery : Detect or intercept enter key pressed example
+9.4k Golang : Detect number of active displays and the display's resolution
+17.8k Golang : Check if a directory exist or not
+9.3k Golang : Read file with ioutil
+45.6k Golang : Read tab delimited file with encoding/csv package
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+13.2k Golang : Read XML elements data with xml.CharData example
+18k Golang : Get path name to current directory or folder
+31.1k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions