Home >Backend Development >Golang >What is the use of golang map?

What is the use of golang map?

(*-*)浩
(*-*)浩Original
2019-12-09 14:03:482966browse

What is the use of golang map?

The map data type is available 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 and addition. , delete and other operations. 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"

The first line of code above does not initialize the map. , but writing to it is a reference to a null pointer, which will cause a painc.

So, you have to 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

often Using map is usually very enjoyable, 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. Therefore, some good habits should be developed at the beginning, such as assertion checking, concurrency safety considerations, etc.

Perhaps you can try sync.Map

The sync.Map in golang is concurrency-safe. In fact, it is a golang-customized structure named Map in the sync package. The structure prototype is as follows:

type Map struct {
   mu Mutex
   read atomic.Value // readOnly
   dirty map[interface{}]*entry
   misses int
}

You can see that there is a Mutex, and it is obvious that a lock mechanism is used to ensure concurrency safety. The Map in this package provides Store, Load, Delete, Range and other operations. And the Map in the sync package is available out of the box, that is, it can be used directly after declaration, as follows:

var m sync.Map
m.Store("method", "eth_getBlockByHash")
value, ok := m.Load("method")
t.Logf("value=%v,ok=%v\n",value,ok)

The above is the detailed content of What is the use of golang map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn