Map in Golang Part-III

Rajat Yadav
2 min readMar 20, 2021

In this article, we will study sync map in goroutine.

Sync map type is specialized map with separate locking mechanism. This type of map is safe for concurrent use by multiple goroutines without additional locking.

Note:- Sync map must not be copied after first use. this may produce concurrency issues.

Declare global variable to access over the program.

var Person sync.Map

Sync map has predefined methods for manipulation of map.

Method Store(Key, value) sets the value for a key.

Person.Store("pi", 3.14)
Person.Store("e", 2.77)
fmt.Println(Person) // error because Println copies value

Method Load(Key) returns the value stored in the map for a key, or nil if no value is present. second returns indicates whether value was found in the map.

if value, ok := Person.Load("pi"); ok {
fmt.Println(value) // 3.14
}

Method Delete(Key) deletes the key from map an does not any value .

Person.Delete("pi")

Method LoadOrStore(Key, Value) returns value and true if Key is present else store the key and its value and return that value and false.

Person.Store("e", 2.77) // 2.77 true
Person.Store("r", 1.77) // 1.77 false

Method Range is used to iterate over the map.

Person.Range(func(k, v interface{}) bool {if v != nil {
fmt.Println(k,v) // prints keys, values
}
return true
})

As mentioned in official documentation of sync map must not be coped after first used. we can achieve this by Range method of sync map.

PersonCopy := make(map[string]int)Person.Range(func(k, v interface{}) bool {if v != nil {
PersonCopy[k.(string)] = v.(int)
}
return true
})

You can run the above program on playground — Link

Thank you !!! .. Feedback will be highly appreciated.

--

--