Get an arbitrary key/item from a map

前端 未结 6 1503
攒了一身酷
攒了一身酷 2021-02-01 12:59

I am new to Go and now I want to get an arbitrary item from a map; what\'s the idiomatic way to do that? I can only think of something like this:

func get_some_k         


        
6条回答
  •  春和景丽
    2021-02-01 13:33

    Here is a more generic version, although it may be less efficient:

        keys := reflect.ValueOf(mapI).MapKeys()
        return keys[rand.Intn(len(keys))].Interface()
    

    https://play.golang.org/p/0uvpJ0diG4e

提交回复
热议问题