Page Content

Tutorials

Maps In GoLang: An Unordered Set Of The Key Value Pairs

Maps in GoLang

A map is a potent built-in data type in Go that denotes an unordered set of key-value pairs. Associative arrays, hash tables, and dictionaries are some of the other names for maps in different computer languages. Searching for a value using its related key is their main purpose.

Key Characteristics of Maps in Go

Key-Value Association: In maps, a key corresponds to a value. An example would be to keep users indexed by their user ID in a map, where the user object is the value and the ID is the key.

Unordered: The order in which map keys iterate is not fixed and may vary from run to run.

Dynamic Size: Maps’ length is dynamic and increases as new objects are added, unlike arrays.

Reference Type: As reference types, maps share the same underlying data whether they are provided to a function or assigned to a new variable. Variables that point to the same map will change in response to changes made to one.

Comparable Keys: A map’s keys need to be similar, although they can be almost any kind. The Go compiler must therefore support the == operator in order to distinguish one key from another. Integers and strings are examples of primitive types. Because different devices and operating systems have varying precision, using floating-point values as keys could cause issues.

Declaring and Initializing Maps in Go

The map keyword can be used to declare a map, followed by the value type and the key type enclosed in brackets. Map[string]int, for instance, can be used to declare a map of strings to integers.

Map initialization can be done in a number ways:

Using make: Before they can be utilized, maps need to be initialized. The maps are allocated using the make built-in function. Additionally, you can preallocate space for many keys, which can enhance speed on bigger maps.

A map’s length is 0 when it is first made with Make.

Using Composite Literals: Maps can be declared and initialised directly. You provide a key and a value of the right kind for every element.

Accessing, Adding, and Modifying Elements

Use brackets ([]) to access maps.

Accessing: Enter the value in the brackets to retrieve it.

Adding/Modifying: By adding a value to a key using the = operator, you can modify existing values or add new key-value pairs. The key is added if it doesn’t already exist and its value is modified if it does.

Attempting to add data to a nil map will make people panic.

Checking Existence (Comma-Ok Idiom)

When a key is accessed that is not present in the map, Go returns the value type’s zero value (for example, “” for text and 0 for int). The comma, ok syntax is provided by Go to differentiate between a stored zero value and a missing key.

name, ok := elements["Un"]
fmt.Println(name, ok) // Prints "" false if "Un" doesn't exist [44, 46]
if name, ok := elements["Un"]; ok {
    fmt.Println(name, ok)
} 

The presence of the key will make the ok variable true; if not, it will be false.

Deleting Elements

You can use the built-in delete function to remove items from a map. It can be called on a non-existent key without generating an error and has no return value.

Setting a map equal to an empty map of the same type will remove all of its values, allowing the old map to be trash collected and creating a new empty map.

Iterating Over Maps in Go

A for loop with the range keyword can be used to iterate over a map. The key and the value for each iteration are the two values that the range keyword returns.

for key, value := range lookup {
    fmt.Println(key, value)
} 

As was already mentioned, there is no order to the iteration across maps.

Common Use Cases Maps in Go

Maps can be used for a variety of purposes.

Lookup tables or dictionaries: For instance, keeping track of chemical elements according to their symbols.

Storing unstructured data: Helpful in situations where keys are decided at runtime.

Grouping data: A map of string symbols to a map with element name and state are examples of complicated data structures made possible by the ability of maps to hold additional maps or slices.

Implementing sets: You can emulate a set in Go by using a map containing boolean values, where the presence of a key with true signals membership, even though Go has an inherent set type.

Go has an extremely quick built-in map implementation. But choosing an effective algorithm and data structure can have a big impact on performance, particularly for applications that handle a lot of data.

You can also read What Is Mean By Object Oriented Programming In GoLang?

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index