Iterare su tutti i tasti di una mappa
-
12-09-2019 - |
Domanda
C'è un modo per ottenere un elenco di tutte le chiavi in un linguaggio Go mappa?Il numero di elementi è dato da len()
, ma se ho una mappa come:
m := map[string]string{ "key1":"val1", "key2":"val2" };
Come faccio a scorrere tutte le chiavi?
Soluzione
https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
o
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Linguaggio Go specifiche per for
istruzioni specifica che il primo valore è la chiave, la seconda variabile è il valore, ma non deve essere presente.
Altri suggerimenti
Ecco qualche facile modo per ottenere slice
di mappa-chiavi.
// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
for k := range m {
keys = append(keys, k)
}
return keys
}
// use `Keys` func
func main() {
m := map[string]interface{}{
"foo": 1,
"bar": true,
"baz": "baz",
}
fmt.Println(Keys(m)) // [foo bar baz]
}
C'è un modo per ottenere un elenco di tutte le chiavi in un linguaggio Go mappa?
ks := reflect.ValueOf(m).MapKeys()
come faccio a scorrere tutte le chiavi?
Utilizzare accettato di rispondere:
for k, _ := range m { ... }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow