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

Go

Example

Go

Result

Go




Using make() Function

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

Syntax

Go

Example

Go

Result

Go





Creating an Empty Map

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

Syntax

Go

Example

Go

Result

Go





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

Go

Example

Go

Result

Go




Updating and Adding Elements

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

Syntax

Go

Example

Go

Result

Go




Removing Elements

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

Syntax

Go

Example

Go

Result

Go




Checking for Specific Elements

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

Syntax

Go

Example

Go

Result

Go




Maps Are References

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

Example

Go

Result

Go





Iterating Over Maps

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

Example

Go

Result

Go




Iterating in a Specific Order

To maintain a specific order, use an additional structure.

Example

Go

Result

Go
Tutorials dojo strip