Skip to content
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

different hash value when struct contains same string #5

Open
Yiling-J opened this issue Dec 7, 2023 · 1 comment
Open

different hash value when struct contains same string #5

Yiling-J opened this issue Dec 7, 2023 · 1 comment

Comments

@Yiling-J
Copy link

Yiling-J commented Dec 7, 2023

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 Yiling-J/theine-go#31

@gu18168
Copy link

gu18168 commented Jan 21, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants