Golang Maps

Golang Maps

Hey there! Let's learn about map data structure in Golang. I already gave a brief introduction to map in this blog, Learn Go (Part-2).

Map

Maps are pretty useful data structures in every programming language, especially in scenarios where we need O(1) retrieval of data.

Quick Overview

If you already knew what exactly is map then you may skip this section. If not here's a brief introduction. Map essentially helps in storing data as key/value pairs. So every data item is a key:value. If we want to access the data, we use the key to get a value associated with that key. In Golang, map is unordered.

package main
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    // keys are "John" and "Stacy"
    // valuesa are 12 and 23
    fmt.Println(someMap["John"]) // prints 12
}

Declaration & Initialization

Map is declared using the following syntax: var someMap map[string]int, means declaring a variable someMap with data type map where the type of key and value are string and int

When comes to initialization, we can use either of the following ways:

  • Literal map

  • make() (built-in function)

The literal declaration is where we provide values while declaring the variable itself, as shown in the above example.

We can also use make() function to initialize.

package main
import "fmt"

func main(){ 
    someMap := make(map[string]int, 5)
    someMap["John"] = 34
    fmt.Println(someMap["John"]) // prints 34
}

make(type, size) is the syntax of make. In the above example, we're creating a map data type with a size of 5. The size argument is optional.

Operations on map

Access items

To access values in the map, we use the key to get its associated value, variable_name["key"]

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    // keys are "John" and "Stacy"
    // valuesa are 12 and 23
    fmt.Println(someMap["John"]) // prints 12
}

Adding Items

To add items to a map we use the same syntax as above, variable_name["key"]=value

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    someMap["Raj"] = 25
    fmt.Println(someMap["Raj"]) // prints 25
}

Delete item

To an item in a map, we use delete() function. delete(map_name, key_name)

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    someMap["Raj"] = 25
    fmt.Println(someMap["Raj"]) // prints 25
    delete(someMap, "Raj")
    fmt.Println(someMap["Raj"]) // prints 0
}

As you can see, after deleting Raj and trying to access it again, we're getting 0 . It's because if the key we're searching for doesn't exist, map returns 0.

To exactly know where is key/value exists in the map, we use the following syntax:

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    someMap["Raj"] = 25
    fmt.Println(someMap["Raj"]) // prints 25
    delete(someMap, "Raj")

    val, exists := someMap["Raj"] // prints 0
    if !exists {
        fmt.Println("Item doesn't exist") 
    }
}

When accessing a key/value, we can use an optional variable exits which holds a boolean value. If the item exists, true, else false.

Update item

Updating is as same as inserting/adding an item.

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23} 
    someMap["Stacy"] = 25
    // Stacy key now holds 25
    fmt.Println(someMap["Stacy"]) // prints 25
}

Clear map items

To clear out all items, we would just reinitialize the map variable.

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23}
    fmt.Println(someMap["Stacy"]) // prints 23
    someMap = make(map[string]int)
    fmt.Println(someMap)          // prints map[]
}

Size of map

Map size is known by using a build-in function called len().

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23}
    fmt.Println("Size is", len(someMap)) // prints 2
}

Iterating using for loop

To iterate over all items of map, we use for loop

package main 
import "fmt"

func main() {
    var someMap = map[string]int{"John":12, "Stacy":23}
    for key, val := range someMap {
        fmt.Printf("Key is %v and value is %v\n", key, val)
    }
}

// output
Key is John and value is 12
Key is Stacy and value is 23