hashmap
hashmap copied to clipboard
different hash value when struct contains same string
here is a simple test to reproduce:
type Foo struct {
Bar string
}
func TestStringStruct(t *testing.T) {
m := New[Foo, int](50)
mg := map[Foo]int{}
for i := 0; i < 50; i++ {
foo := Foo{Bar: strconv.Itoa(i + 100)}
mg[foo] = i
if v := mg[Foo{Bar: strconv.Itoa(i + 100)}]; v != i {
t.Fatal()
}
}
for i := 0; i < 50; i++ {
foo := Foo{Bar: strconv.Itoa(i + 100)}
m.Set(foo, i)
if v, _ := m.Get(Foo{Bar: strconv.Itoa(i + 100)}); v != i {
t.Fatal()
}
}
}
This is related to https://github.com/Yiling-J/theine-go/issues/31
This should be expected behavior at this point? Because the hash function actually assumes that the key type should be a value type (or a struct without pointers). The string
actually contains a pointer. So even though the two strings have the same value, the pointers have different addresses, so the calculated hash values are different.
I see that other map libraries can't actually handle this either, ref: https://github.com/cornelk/hashmap/blob/main/util_hash.go