Go - Decoding gob Format Data to Structs

发布时间 2023-10-05 10:00:46作者: ZhangZhihuiAAA

Problem: You want to decode gob format data back to structs.


Solution: Use the encoding/gob package to decode the gob format data back to structs.

 

func   read ( data   interface {},   filename   string )   { 
      file ,   err   :=   os . Open ( "reading" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  read  file:" ,   err ) 
      } 
      decoder   :=   gob . NewDecoder ( file ) 
      err   =   decoder . Decode ( data ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  decode  data:" ,   err ) 
      } 
}

Open the file named reading , which you created from the previous recipe. This file will be your Reader . You will create a decoder around the reader and then call Decode on it, passing the struct instance to be populated with the data.
Call the read function and pass in a reference to a struct instance:

read ( & reading ,   "reading" )

The reading struct instance will be populated with the data after the call.

Encoding gob, as you can see, is faster than encoding JSON, though the amount of memory used is the same. Decoding gob is much faster than decoding JSON as well and uses a lot less memory.