A type constraint is an interface type that restricts which types may be supplied as generic type arguments. For a generic map-key function, comparable permits keys usable with == or !=, unlike any, which would allow invalid slice keys. section 2.9.1
func getKeys[K comparable, V any](m map[K]V) []K { #1
var keys []K #2
for k := range m {
keys = append(keys, k)
}
return keys
}
A comparable constraint lets getKeys accept any comparable key type while leaving the value type unrestricted. section 2.9.1
Choose the constraint according to the permitted type set:
- Use comparable when every comparable key type is acceptable. section 2.9.1
- Define a custom interface constraint with a union such as ~int | ~string when the set must be narrower. section 2.9.1
- Use ~int rather than int when named types with int as their underlying type should also satisfy the constraint. section 2.9.1
- Combine an underlying-type approximation with methods when accepted custom types must also provide behavior such as String() string. section 2.9.1
Inference at the call site
Given a map[string]int, getKeys(m) infers string as the key type; getKeys[string](m) states that type argument explicitly. section 2.9.1





