Go Maps

Maps in Go are collections that store data as key-value pairs, where each unique key is linked to a value. These are unordered, dynamic, and do not allow duplicate keys. The len() function gives the total number of elements in a map, and their default value is nil. Internally, maps use hash tables for efficient data management.

Tutorials dojo strip



Creating Maps

Using var and := Syntax

Maps can be initialized using the var keyword or the shorthand := syntax.

Syntax

var mapName = map[KeyType]ValueType{key1: value1, key2: value2, ...}
mapName := map[KeyType]ValueType{key1: value1, key2: value2, ...}

Example

package main
import ("fmt")

func main() {
  var motorcycles = map[string]string{"brand": "Honda", "model": "CB500F", "year": "2022"}
  cars := map[string]int{"SUV": 5, "Sedan": 3, "Truck": 7}

  fmt.Printf("motorcycles\t%v\n", motorcycles)
  fmt.Printf("cars\t%v\n", cars)
}

Result

motorcycles    map[brand:Honda model:CB500F year:2022]
cars           map[Truck:7 Sedan:3 SUV:5]




Using make() Function

The make() function is commonly used to create maps.

Syntax

var mapName = make(map[KeyType]ValueType)
mapName := make(map[KeyType]ValueType)

Example

package main
import ("fmt")

func main() {
  var motorcycles = make(map[string]string)
  motorcycles["brand"] = "Yamaha"
  motorcycles["model"] = "R3"
  motorcycles["year"] = "2021"

  cars := make(map[string]int)
  cars["SUV"] = 4
  cars["Sedan"] = 3
  cars["Truck"] = 6

  fmt.Printf("motorcycles\t%v\n", motorcycles)
  fmt.Printf("cars\t%v\n", cars)
}

Result

motorcycles    map[brand:Yamaha model:R3 year:2021]
cars           map[Truck:6 Sedan:3 SUV:4]





Creating an Empty Map

An empty map can be created using make() (preferred) or by defining its type.

Syntax

var mapName = make(map[KeyType]ValueType)  // Recommended
var mapName map[KeyType]ValueType          // May cause runtime panic if written to

Example

package main
import ("fmt")

func main() {
  var motorcycles = make(map[string]string)
  var cars map[string]string

  fmt.Println(motorcycles == nil) // false
  fmt.Println(cars == nil)        // true
}

Result

false
true





Allowed Key Types

Map keys can be of types that support the equality operator (==), including:

  • Booleans
  • Numbers
  • Strings
  • Arrays
  • Pointers
  • Structs
  • Interfaces (if the dynamic type supports equality)

Invalid key types include:

  • Slices
  • Maps
  • Functions (since the equality operator is not defined for them)

For values, any type is allowed.




Accessing Map Elements

Elements of a map can be accessed using their keys.

Syntax

value = mapName[key]

Example

package main
import ("fmt")

func main() {
  motorcycles := map[string]string{"brand": "Suzuki", "model": "GSX-R750", "year": "2023"}
  fmt.Println(motorcycles["brand"])
}

Result

Suzuki




Updating and Adding Elements

Maps allow you to update existing elements or add new ones by assigning values to keys.

Syntax

mapName[key] = value

Example

package main
import ("fmt")

func main() {
  cars := make(map[string]string)
  cars["brand"] = "BMW"
  cars["model"] = "M3"
  cars["year"] = "2019"

  fmt.Println(cars)

  cars["year"] = "2022" // Updating an element
  cars["color"] = "blue" // Adding an element

  fmt.Println(cars)
}

Result

map[brand:BMW model:M3 year:2019]
map[brand:BMW color:blue model:M3 year:2022]




Removing Elements

The delete() function is used to remove elements from a map.

Syntax

delete(mapName, key)

Example

package main
import ("fmt")

func main() {
  motorcycles := map[string]string{"brand": "Ducati", "model": "Monster", "year": "2020"}
  fmt.Println(motorcycles)

  delete(motorcycles, "year")
  fmt.Println(motorcycles)
}

Result

map[brand:Ducati model:Monster year:2020]
map[brand:Ducati model:Monster]




Checking for Specific Elements

To check if a certain key exists, use the val, ok pattern.

Syntax

val, ok := mapName[key]

Example

package main
import ("fmt")

func main() {
  motorcycles := map[string]string{"brand": "Triumph", "model": "Bonneville", "year": "2017"}

  val1, ok1 := motorcycles["brand"]
  val2, ok2 := motorcycles["color"]
  _, ok3 := motorcycles["model"]

  fmt.Println(val1, ok1)
  fmt.Println(val2, ok2)
  fmt.Println(ok3)
}

Result

Triumph true
 false
true




Maps Are References

Maps are reference types, meaning changes in one variable reflect in others pointing to the same map.

Example

package main
import ("fmt")

func main() {
  cars := map[string]string{"brand": "Tesla", "model": "Model 3", "year": "2021"}
  electricCars := cars

  fmt.Println(cars)
  fmt.Println(electricCars)

  electricCars["year"] = "2023"
  fmt.Println("After change to electricCars:")

  fmt.Println(cars)
  fmt.Println(electricCars)
}

Result

map[brand:Tesla model:Model 3 year:2021]
map[brand:Tesla model:Model 3 year:2021]
After change to electricCars:
map[brand:Tesla model:Model 3 year:2023]
map[brand:Tesla model:Model 3 year:2023]





Iterating Over Maps

Maps can be iterated using the range keyword. Keep in mind the order is not guaranteed.

Example

package main
import ("fmt")

func main() {
  motorcycles := map[string]int{"Sport": 1, "Adventure": 2, "Cruiser": 3, "Touring": 4}

  for k, v := range motorcycles {
    fmt.Printf("%v : %v, ", k, v)
  }
}

Result

Touring : 4, Cruiser : 3, Sport : 1, Adventure : 2,




Iterating in a Specific Order

To maintain a specific order, use an additional structure.

Example

package main
import ("fmt")

func main() {
  motorcycles := map[string]int{"Sport": 1, "Adventure": 2, "Cruiser": 3, "Touring": 4}
  order := []string{"Sport", "Adventure", "Cruiser", "Touring"}

  for _, key := range order {
    fmt.Printf("%v : %v, ", key, motorcycles[key])
  }
}

Result

Sport : 1, Adventure : 2, Cruiser : 3, Touring : 4,
Tutorials dojo strip
Scroll to Top