The map data type is found in many languages. It is a hash table in the form of key and value, so that key and value can be mapped one by one for fast search, addition, deletion, etc. operate. The Go language is no exception, providing the map data structure type.
# (Recommended learning: Go )
Golang, the map is a reference type, such as Like pointer slicing, it points to nil after being declared with the following code. This is also explained in the golang official documentation, so never use it directly after declaring it. You may often make the following mistakes at first:var m map[string]string m["result"] = "result"
So, you must remember to use the make function to allocate memory and initialize it:
m := make(map[string]string) m["result"] = "result"
map in golang is not concurrency safe
I often use map, and it feels good to use it, but suddenly one day the traffic increases, and the program hangs up without knowing it. I don’t know what happened, but it was working fine before. So some good habits should be developed at the beginning, such as assertion checking, concurrency safety considerations, etc. Even though map is easy to use, you have to be careful. Perhaps many people still don't know that Golang's built-in map is not actually concurrency-safe.Maybe you can try sync.Map
The sync.Map in golang is concurrency safe. In fact, it is a custom name of golang in the sync package. Map structure. The structure prototype is as follows:type Map struct { mu Mutex read atomic.Value // readOnly dirty map[interface{}]*entry misses int }
The above is the detailed content of Why is golang map not concurrent?. For more information, please follow other related articles on the PHP Chinese website!