Search code examples
godecodinggob

Golang convert gob string to interface


I am making a go program where I need to write a gob to a file. I used the .String() method to convert the gob to a string.

var network bytes.Buffer
encoder := gob.NewEncoder(&network)

_ = encoder.Encode(valueToEncode)

gobString := network.String()

then I will write the gob to a file, and later I will retrieve it and send it to this program:

var filebytes = []byte(file)  //i think that these two lines are the issue
network := bytes.NewBuffer(filebytes)

decoder := gob.NewDecoder(network)

var decoded interface{}

_ := decoder.Decode(&decoded)

but when i run this, it gives me this error:

gob: encoded unsigned integer out of range

I think the issue is with the first two lines of the decoder program. So what should I put to properly decode the gob?

EDIT: What I want is a .UnString() method for the gobString. How can i achieve that?


Solution

  • The encoding/gob generates binary data from Go values. The result is not for textual representation, so you should not treat it as a string, but as a series of bytes, e.g. []byte.

    That said, do not use Buffer.String() but rather Buffer.Bytes() if you must obtain the encoded data.

    Here's an example encoding and decoding a string value using encoding/gob:

    // ENCODE
    var network bytes.Buffer
    encoder := gob.NewEncoder(&network)
    
    valueToEncode := "Hello, 世界"
    if err := encoder.Encode(valueToEncode); err != nil {
        panic(err)
    }
    
    gobData := network.Bytes() // Save / serialize this byte slice
    
    // DECODE
    network2 := bytes.NewBuffer(gobData)
    decoder := gob.NewDecoder(network2)
    
    var decoded string
    if err := decoder.Decode(&decoded); err != nil {
        panic(err)
    }
    fmt.PrintTln(decoded)
    

    Output (try it on the Go Playground):

    Hello, 世界
    

    Also note that if you intend to write the encoded data into a network connection or a file, you don't need bytes.Buffer, you can directly encode to those. If you must use bytes.Buffer, you may also use its Buffer.WriteTo() method to write its contents into an io.Writer (such as a file or network connection).