38 lines
1.2 KiB
Go
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
|
|
}
|