Go Maps

Go Tutorial

Go (Golang) – Maps

A map in Go is a built-in reference data type that stores data in key–value pairs.
Maps are commonly used for fast lookups, dictionaries, and configurations.


 Declaring

Using make()

Short Declaration


 Initializing Maps with Values


 Adding & Updating Map Elements


 Accessing Map Elements

⚠ If key does not exist, Go returns zero value.


 Checking if Key Exists (Important)


 


 Deleting Map Elements


 Looping Through

⚠ Map iteration order is random.


 Map with Different Data Types


 Map of Slices


 Nested


 Reference Types


 


 Nil Map vs Empty Map

  •  Writing to nil map causes panic
  •  Reading from nil map is allowed

 Map Keys – Rules

  •  Keys must be comparable
  • Slices, maps, functions cannot be keys

Valid keys:


Best Practices

  •  Always initialize before writing
  •  Use comma ok to check existence
  •  Avoid relying on order
  •  Use It for fast lookups

Summary

  • It store key–value pairs

  • Reference type

  • Fast access

  • Unordered collection

You may also like...