MCPcopy Create free account
hub / github.com/benbjohnson/immutable / NewComparer

Function NewComparer

immutable.go:2365–2380  ·  view source on GitHub ↗

NewComparer returns the built-in comparer for a given key type. Note that only int-ish and string-ish types are supported, despite the 'comparable' constraint. Attempts to use other types will result in a panic - users should define their own Comparers for these cases.

(key K)

Source from the content-addressed store, hash-verified

2363// Note that only int-ish and string-ish types are supported, despite the 'comparable' constraint.
2364// Attempts to use other types will result in a panic - users should define their own Comparers for these cases.
2365func NewComparer[K any](key K) Comparer[K] {
2366 // Attempt to use non-reflection based comparer first.
2367 switch (any(key)).(type) {
2368 case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, string:
2369 return &defaultComparer[K]{}
2370 }
2371 // Fallback to reflection-based comparer otherwise.
2372 // This is used when caller wraps a type around a primitive type.
2373 switch reflect.TypeOf(key).Kind() {
2374 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String:
2375 return &reflectComparer[K]{}
2376 }
2377 // If no comparers match then panic.
2378 // This is a compile time issue so it should not return an error.
2379 panic(fmt.Sprintf("immutable.NewComparer: must set comparer for %T type", key))
2380}
2381
2382// defaultComparer compares two values (int-ish and string-ish types are supported). Implements Comparer.
2383type defaultComparer[K any] struct{}

Callers 2

setMethod · 0.85
testNewComparerFunction · 0.85

Calls

no outgoing calls

Tested by 1

testNewComparerFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…