Get an arbitrary key/item from a map

前端 未结 6 1485
攒了一身酷
攒了一身酷 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:23

    Whether getting an arbitrary key from a hash table is a common requirement may be discussed. Other language map implementations often lack this feature (eg. Dictionary in C# )

    However, your solution is probably the fastest one, but you will be left with a pseudo-random algorithm that you do not control. And while the current implementation uses a pseudo-random algorithm, the Go Specification doesn't give you any assurance it will actually be random, only that it is not guaranteed to be predictable:

    The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

    If you want more control of the randomization, you can also in parallel keep an updated slice of values (or keys) contained in the map, using the randomization of your choice (math/rand or crypto/rand for more extreme cases) to get the value stored at an index, selected randomly, in the slice.

提交回复
热议问题