Files
go-cuckoo/compare_example_test.go
M.V. Hutz b762417b80
All checks were successful
CI / lint (pull_request) Successful in 51s
CI / unit-test (pull_request) Successful in 25s
CI / mutation-test (pull_request) Successful in 2m44s
CI / fuzz-test (pull_request) Successful in 1m2s
chore: move from tools/dsa
Moved the implementation of this hash table from `tools/dsa` #1.
2026-03-16 21:10:08 -04:00

38 lines
1.2 KiB
Go

package cuckoo_test
import (
"fmt"
"git.maximhutz.com/tools/go-cuckoo"
)
// This example demonstrates what happens when EqualFunc and Hash disagree on
// equality. Although 'isEqual' only compares user IDs, but the hashes use the
// entire 'User' object. So, two objects with the same ID but different names
// hash to different slots, so the table cannot find them.
func ExampleEqualFunc_badEqualFunc() {
type User struct{ ID, Name string }
// Two users with the same ID are equal.
isEqual := func(a, b User) bool { return a.ID == b.ID }
hashA, hashB := cuckoo.NewDefaultHash[User](), cuckoo.NewDefaultHash[User]()
userbase := cuckoo.NewCustomTable[User, bool](hashA, hashB, isEqual)
(userbase.Put(User{"1", "Robert Doe"}, true))
fmt.Println("Has Robert?", userbase.Has(User{"1", "Robert Doe"}))
fmt.Println("Has Johanna?", userbase.Has(User{"2", "Johanna Smith"}))
// The hashes are different, so even though the equal function returns true,
// the table does not recognize it.
fmt.Println("Equal?", isEqual(User{"1", "Rob Doe"}, User{"1", "Robert Doe"}))
fmt.Println("Has Rob?", userbase.Has(User{"1", "Rob Doe"}))
// Output:
// Has Robert? true
// Has Johanna? false
// Equal? true
// Has Rob? false
}