Keys of a map
-
keys
-
There is no function to fetch the list of keys.
-
We can iterate over the keys and put them in an slice with pre-allocated size.
package main
import (
"fmt"
)
func main() {
scores := map[string]int{"Alma": 23, "Cecilia": 12, "Berta": 78, "David": 37}
fmt.Println(len(scores))
fmt.Println(scores)
names := make([]string, 0, len(scores))
for name := range scores {
names = append(names, name)
}
fmt.Println(names)
for _, name := range names {
fmt.Println(name)
}
}
4
map[Alma:23 Berta:78 Cecilia:12 David:37]
[Alma Cecilia Berta David]
Alma
Cecilia
Berta
David