Go Map
In Go, Maps is an unordered collection of key and its associated value. They are very good for looking up values fast. The key type must have the operations == and != defined, like string, int, float.
Hence arrays, slices and structs cannot be used as key type, but pointers and interface types can.
structs can be used as a key when we provide Key() or Hash() method, so that a unique numeric or string key can be calculated from the struct’s fields.
A map is a reference type and declared in general as:
e.g.
Go Map Example
Output:
map[John:37 Raj:20 Kate:28] 20
Go Map Insert and Update operation
Update and insert operation are similar in go map. If the map does not contain the provided key the insert operation will takes place and if the key is present in the map then update operation takes place.
Output:
map[] map[Key3:30 Key1:10 Key2:20] map[Key1:10 Key2:555 Key3:30]
Go Map Delete operation
You can delete an element in Go Map using delete() function.
Syntax:
Example:
Output:
map[Key1:10 Key2:20 Key3:30] map[Key2:20 Key1:10]
Go Map Retrieve Element
Syntax:
Example:
Output:
map[Key1:10 Key2:20 Key3:30] The value: 20
We can also test if a key is present in the table with two value example
syntax:
If key is not present, then the value of elem is the default value of element type.
If the type of elem is int then value of elem is zero.
Output:
map[Key1:10 Key2:20 Key3:30] The value: 20 Present? true The value: 0 Present? false
In Go, Maps are like struct, but it requires keys
Go Map of Struct
Output:
map[tutoraspire:{40.68433 -74.39967} SSS-IT:{37.42202 -122.08408}]