Both map and struct in the go language can indicate which one to use when using key/value,.

both map and struct in the go language can indicate how to determine whether to use map or struct? when using key/value,.

Nov.05,2021

when you know the received data structure and can abstract it, use struct
if you don't know how to store it / temporarily / or don't know how to deal with it, use map


I don't think struct is designed to simply store KV data structures.
refer to some open source frameworks and built-in modules. The data structures defined by struct are generally more complex data structures. Comparing two typical uses,
the following code comes from url package

 

the functions of map and struct are not the same.

  • map is used to form an one-to-one mapping for the purpose of finding data quickly.
  • struct is used to combine multiple data into a single data volume, in a composite way, to represent real objects with data.

therefore, if you need kv, to give priority to kv, consider using sync.Map in concurrent scenarios.

Menu