

The sync.Map type stores keys and values of any type (using the empty interface). package mainīecause concurrent goroutines are used so commonly in Go, the standard library has a specialized data structure that acts like a normal map, but is perfectly safe to be read and written to across multiple goroutines without the use of an external mutex. NoLower Option noLower // Compact omits mappings in case folding for characters that would grow the // input. var ( // NoLower disables the lowercasing of non-leading letters for a title // caser. Also note that we still don’t need to lock the mutex when we’re reading - unless another goroutine may be writing at the same time, which may often be the case in real-world code. An Option is used to modify the behavior of a Caser.


Note that we use a defer statement to trigger an automatic unlock of the mutex when the function ends. So in the example below where we start up goroutines to increment the map values, it’s necessary to use a mutex. However, we cannot safely write to maps concurrently.
#Golang maps godocs code
Each goroutine calls a method on the WaitGroup to show that it has finished: it does this using the defer keyword, so that the other code in the goroutine is run first. We use the sync.WaitGroup data structure, so that the main function doesn’t end until all the goroutines that are started in the for-loop have completed. For example, we could start five goroutines and get them each to print out the stringified map, and that wouldn’t pose a problem. Let’s say that we’re counting the number of cats and dogs that are housed in kennels that we run. So in the example below, we’re storing an integer for each string. The key-type goes inside the square brackets and the value-type follows them. Before it can be used, each map has to be initialized with the make function.
