4

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?

3
  • Decoding a gob-encoded string value into an interface{} gives another error: local interface type *interface {} can only be decoded from remote interface type; received concrete type string, so please provide a minimal reproducible example that produces your error. Commented May 6, 2020 at 17:22
  • The code I gave throws the unsigned integer out of range error for me Commented May 6, 2020 at 17:23
  • The code you posted is incomplete and would give a compile-time error on its own. There are other parts which you didn't show. I tried to make it a minimal, running example and got the error I posted above. So please provide a minimal reproducible example that reproduces your error so we can help with your actual error. Commented May 6, 2020 at 17:24

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.