-
Notifications
You must be signed in to change notification settings - Fork 3
Maps
Openweb edited this page Oct 5, 2020
·
4 revisions
Maps are a reference to hash-table. It is unordered collection of key-value pairs. It is written as map[K]v
where all keys K
are same type and are comparable. Similarly all values V
are similar type. Though floating points are comparable DO NOT use them as keys.
// Declare a map of strings and floats as:
var shop map[string]float32
shop = make(map[string]float32) // creates a map
// Access the map using keys as:
shop["Sunnyvale Square Shopping Center"] = 34.56
shop["Rose Cart Florist"] = 34.56
- Declare and then create using
make
as in example above. - Use
map literal
to define in place, eg:
shop := map[string]float{
"Sunnyvale Square Shopping Center": 34.56,
"Rose Cart Florist": 34.56,
}
Maps are passed as a reference to functions, though technical details are a bit involved. Read up If a map isn’t a reference variable, what is it? In short:
- A map value is a pointer to a runtime.hmap structure.
- Maps, like channels, but unlike slices, are just pointers to runtime types.
// addSomeUSStates will add or override these keys in caller
func addSomeUSStates(m map[string]string) {
m["al"] = "ALABAMA"
m["ca"] = "CALIFORNIA"
m["co"] = "COLORDO"
m["fl"] = "FLORIDA"
}
func main() {
// Create a map and add some values to it.
m := make(map[string]string)
m["ga"] = "GEORGIA" // Some inital values
m["nv"] = "NEVADA"
addSomeUSStates(m) // Note that more k/v will be added.
}
You can choose any key
type as long as it is comparable and there is no restriction on value
type.
- Map of keys of struct and value of struct type
- Map of keys of struct and value as array type
- Map of keys of array and value as struct type
- Map of keys of string type and value of map type