New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
encoding/gob: non-nil empty slices encoded/decoded as nil #10905
Comments
I don't see why this is a bug. From the encoding/gob docs:
Your existing nil slice does, in fact, have capacity for 0 elements, so no new slice needs to be created. |
Oh maybe I get it. When decoding, it doesn't necessarily allocate a new slice. It just tries to append the encoded elements to the destination slice. And since there are no encoded elements, nothing happens. Is that correct? |
From encoding/gob's point of view, []byte{} and []byte(nil) are
not differentiable.
This is working as intended.
|
Thanks, sorry for wasting your time |
What is the workaround for the issue, btw? I faced exactly the same problem recently: http://play.golang.org/p/lSFZCkPaRd |
There is no general workaround, your code just has to deal with this in a specific way that depends on what you are trying to accomplish. |
json encode is working differently in that case (and I think properly), Becuase of that users might face this kinde of inconsistancies: (lint to playground) package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
)
type User struct {
FriendIDs []int `json:friends`
}
func main() {
var network bytes.Buffer
enc := gob.NewEncoder(&network)
dec := gob.NewDecoder(&network)
inUser1 := User{nil}
inUser2 := User{[]int{}}
inJson1, _ := json.Marshal(inUser1)
inJson2, _ := json.Marshal(inUser2)
_ = enc.Encode(inUser1)
_ = enc.Encode(inUser2)
var outUser1 User
var outUser2 User
_ = dec.Decode(&outUser1)
outJson1, _ := json.Marshal(outUser1)
_ = dec.Decode(&outUser2)
outJson2, _ := json.Marshal(outUser2)
fmt.Printf("outJson1: %s\n", outJson1)
fmt.Printf(" inJson1: %s\n", inJson1)
fmt.Printf("outJson2: %s\n", outJson2)// here is the issue gob is treating nil and []int{} same way when json is treating them properly
fmt.Printf(" inJson2: %s\n", inJson2)
} I think gob should trate |
Take an empty slice (non nil), encode it with gob, decode it again and you get a nil slice:
https://play.golang.org/p/WI8NCohVua
(I only tested on the playground for now)
The text was updated successfully, but these errors were encountered: