Search code examples
gogob

trying to understand how the Go gob encoder works


in my ambitions to understand how gob work . i have severals question .

i know that gob serialize a go type like struct map or interface(we must register it's real type) but :

func (dec *Decoder) Decode(e interface{}) error
Decode reads the next value from the input stream and stores it in the data represented by the       
empty interface value.
If e is nil, the value will be discarded. 
Otherwise, the value underlying e must be a pointer to the correct type for the next data item received.
If the input is at EOF, Decode returns io.EOF and does not modify e.

i didn't understand nothing in this documentation . what they mean by ( reads the next value from the input stream ) they are one data that we could send it's a struct or a map but not many .what they mean by If e is nil, the value will be discarded. please expert explain to me i'am disasperate all day and ididn't find nothing


Solution

  • Since entering this answer, I learned that OP is trolling us. Stop feeding the troll.

    You can write multiple values to a stream. You can read multiple values from a stream.

    This code writes two values to output stream w, an io.Writer:

    e := gob.NewEncoder(w)
    err := e.Encode(v1)
    if err != nil {
       // handle error
    }
    err := e.Encode(v2)
    if err != nil {
      // handle error
    }
    

    This code reads the values from stream r, an io.Reader. Each call to Decode reads a value that was written by a call to Decode.

    d := gob.NewDecoder(r)
    var v1 V
    err := e.Decode(&v1)
    if err != nil {
       // handle error
    }
    var v2 V
    err := e.Decode(&v2)
    if err != nil {
      // handle error
    }
    

    Writing multiple values to a stream gains efficiency because information about each encoded type is written once to the stream.