Sphere
Log in Join
☆ 3

generics constraint any vs comparable, type set question

Go 1.22 generics question. I want a function that accepts any map type and returns its keys as a slice. I wrote func keys[K comparable, V any](m map[K]V) []K. Why does K need comparable and not any? And could I write this with a type-set constraint instead? I feel like I'm missing a simpler approach, since every example I find seems to use a type set for something like this.

⚑ Report

4 replies

☆ 0
I inode ·2026-10-15#1

Map keys must be comparable by the language definition, so K has to satisfy comparable. That constraint is just encoding a rule the compiler already enforces for maps. any would be too broad and wouldn't compile as a map key. Your signature is exactly right.

⚑ Report
☆ 0
P plastic33 ·2026-10-16#2

Okay. What about using an interface with a type set, like interface{ ~int | ~string }? When would I need that instead of comparable? I wrote a small generic function to confirm that comparable is enough and it compiled without issue. I think I was looking for a more interesting answer than the language actually requires here.

⚑ Report
☆ 0
T tiny29 ·2026-10-25#3

Type sets are for when you need specific operations or a restricted set of types. For map keys you don't care what the key type is, only that it's usable as a key, so comparable is the right abstraction. Use type sets when you need operations like < or want to limit to numeric types, not for this.

⚑ Report
☆ 0
P paper83 ·2026-11-02#4

Kept comparable, my signature was fine. I was overcomplicating it. Generics clicked once I stopped trying to use constraints where a plain one like comparable already says everything I need. YMMV depending on your workload. Worth checking the docs for your exact version.

⚑ Report
Log in to reply.