Generics Basics
Map Key Helper
The comparable constraint allows a generic helper to use map keys.
Map Key Helper
map_key_helper.go
package main
import "fmt"
// Generic shape: Lookup[K comparable, V any](items map[K]V, key K) (V, bool)
func LookupScore(items map[string]int, key string) (int, bool) {
value, ok := items[key]
return value, ok
}
func main() {
var key =
scores := map[string]int{"alpha": 10, "beta": 20}
value, ok := LookupScore(scores, key)
fmt.Println("key=", key)
fmt.Println("found=", ok)
fmt.Println("value=", value)
}
package main
import "fmt"
// Generic shape: Lookup[K comparable, V any](items map[K]V, key K) (V, bool)
func LookupScore(items map[string]int, key string) (int, bool) {
value, ok := items[key]
return value, ok
}
func main() {
var key =
scores := map[string]int{"alpha": 10, "beta": 20}
value, ok := LookupScore(scores, key)
fmt.Println("key=", key)
fmt.Println("found=", ok)
fmt.Println("value=", value)
}
package main
import "fmt"
// Generic shape: Lookup[K comparable, V any](items map[K]V, key K) (V, bool)
func LookupScore(items map[string]int, key string) (int, bool) {
value, ok := items[key]
return value, ok
}
func main() {
var key =
scores := map[string]int{"alpha": 10, "beta": 20}
value, ok := LookupScore(scores, key)
fmt.Println("key=", key)
fmt.Println("found=", ok)
fmt.Println("value=", value)
}
comparable
Map keys must be comparable, so a generic map helper can require `K comparable`. The trace uses a concrete string-keyed map and shows the generic shape in a comment.