rampatowl
rampatowl

Reputation: 1772

DeepEqual incorrect after serializing map into gob

I've encountered some strange behavior with reflect.DeepEqual. I have an object of type map[string][]string, with one key whose value is an empty slice. When I use gob to encode this object, and then decode it into another map, these two maps are not equal according to reflect.DeepEqual (even though the content is identical).

package main

import (
    "fmt"
    "bytes"
    "encoding/gob"
    "reflect"
)

func main() {
    m0 := make(map[string][]string)
    m0["apple"] = []string{}

    // Encode m0 to bytes
    var network bytes.Buffer
    enc := gob.NewEncoder(&network)
    enc.Encode(m0)

    // Decode bytes into a new map m2
    dec := gob.NewDecoder(&network)
    m2 := make(map[string][]string)
    dec.Decode(&m2)

    fmt.Printf("%t\n", reflect.DeepEqual(m0, m2)) // false
    fmt.Printf("m0: %+v != m2: %+v\n", m0, m2) // they look equal to me!
}

Output:

false
m0: map[apple:[]] != m2: map[apple:[]]

A couple notes from follow-up experiments:

If I make the value of m0["apple"] a nonempty slice, for example m0["apple"] = []string{"pear"}, then DeepEqual returns true.

If I keep the value as an empty slice but I construct the identical map from scratch rather than with gob, then DeepEqual returns true:

m1 := make(map[string][]string)
m1["apple"] = []string{}
fmt.Printf("%t\n", reflect.DeepEqual(m0, m1)) // true!

So it's not strictly an issue with how DeepEqual handles empty slices; it's some strange interaction between that and gob's serialization.

Upvotes: 2

Views: 460

Answers (1)

icza
icza

Reputation: 417592

This is because you encode an empty slice, and during decoding the encoding/gob package only allocates a slice if the one provided (the target to decode into) is not big enough to accomodate the encoded values. This is documented at: gob: Types and Values:

In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream.

Since there are 0 elements encoded, and a nil slice is perfectly capable of accomodating 0 elements, no slice will be allocated. We can verify this if we print the result of comparing the slices to nil:

fmt.Println(m0["apple"] == nil, m2["apple"] == nil)

Output of the above is (try it on the Go Playground):

true false

Note that the fmt package prints nil slice values and empty slices the same way: as [], you cannot rely on its output to judge if a slices is nil or not.

And reflect.DeepEqual() treats a nil slice and an empty but non-nil slice different (non-deep equal):

Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Upvotes: 2

Related Questions