Overview and Introduction to Maps in Go

Welcome aboard for our journey with Go's maps. Maps, a built-in data type, make it easy to organize and find data within collections — a crucial feature for effective programming.

In Go, maps link one value (the key) to another value. Just imagine having a roster of students alongside their grades. With maps, you can quickly associate each student (the key) with their corresponding grade (the value).

Our quest today involves the following:

  • Understanding how to craft and initiate Go's maps.
  • Learning to interact with map elements.
  • Fathoming the external behavior of maps as reference types in Go.

Let's dive in!

Declaring and Initializing Maps in Go

Declaring a map in Go is as easy as pie. For this purpose, you can utilize either the make function or a composite literal. Let's sketch an illustration:

// Using the make function
var grades1 = make(map[string]int)

// Using composite literal syntax
var grades2 = map[string]int{}

// Pre-populated map using composite literal syntax
var grades3 = map[string]int{"John": 85, "Jane": 90}

As displayed above, we create maps that accommodate strings as keys and integers as their associated values.

Working with Maps

Go's maps enable swift and effortless handling of map elements. Adding, changing, accessing values, or handling absent keys in a map is a cinch:

var grades = make(map[string]int)
grades["John"] = 85   // Store John's grade in the map
grades["Jane"] = 90   // Store Jane's grade

johnGrade := grades["John"]     // Retrieve John's grade
grades["John"] = 95             // Update John's grade

delete(grades, "John")            // Delete John's entry
johnGrade, johnExists := grades["John"]   // Check if John's grade exists
if (johnExists) {
    fmt.Println(johnGrade)  // won't execute, as John was deleted
}

Notice how we use the key to access, update or delete an element. It is much more handy then indicies in the array. We can access "John"'s grade using his own name as an identifier!

Maps and Reference Types

Since maps are reference types in Go, assigning a map to a new map variable creates a reference, not a replica:

var originalData = map[string]int{"apple": 1, "banana": 2}
var copiedData = originalData
copiedData["apple"] = 100

fmt.Println(originalData)
fmt.Println(copiedData)

The output of both maps reflects the value 100 related to "apple". Here, copiedData is simply a reference to originalData, hence modifications enacted on copiedData affect originalData.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal