Skip to content
Openweb edited this page Oct 5, 2020 · 4 revisions

Go Maps

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

Initialization

  1. Declare and then create using make as in example above.
  2. Use map literal to define in place, eg:
shop := map[string]float{
  "Sunnyvale Square Shopping Center": 34.56,
  "Rose Cart Florist": 34.56,
}

Maps passing to func

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:

  1. A map value is a pointer to a runtime.hmap structure.
  2. Maps, like channels, but unlike slices, are just pointers to runtime types.

See example in playground:

// 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.
}

Examples

You can choose any key type as long as it is comparable and there is no restriction on value type.

  1. Map of keys of struct and value of struct type
  2. Map of keys of struct and value as array type
  3. Map of keys of array and value as struct type
  4. Map of keys of string type and value of map type

Go play with simple map example.

Clone this wiki locally