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.
Aucun commentaire:
Enregistrer un commentaire