Go Language - Maps - Example

A map is an unordered collection of key/value pairs, where each key is unique. We can create a new map with a make statement or a map literal. The default zero value of a map is nil. The len function returns the size of a map. Go Range keyword is used in different kinds of data structures in order to iterate over elements.

Create a Map:

Create a Map called users that will store int keys and String values:
/* Create a new map
* Empty map of string-string pairs
*/
users := make(map[int]string)

Add Items:

Add a new key-value pair,
//Add Items
users[1] = "scott"
users[2] = "june"
users[3] = "april"
users[4] = "carl"
users[5] = "rick"
users[6] = "daryl"

Update Value:

// Update value
users[6] = "michonne"

Iterate over all keys and values:

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

Access an Item:

//Access an Item
fmt.Println("\n", users[1], "\n")

Remove an Item:

//Remove an Item
delete(users, 3)

Test if entry is present in the map or not:

// Test if entry is present in the map or not
_, status := users[4]
fmt.Println("\n", status, "\n")


Complete Code:

package main

import "fmt"

//Required imports

func main() {

/* Create a new map
* Empty map of string-string pairs
*/
users := make(map[int]string)

//Add Items
users[1] = "scott"
users[2] = "june"
users[3] = "april"
users[4] = "carl"
users[5] = "rick"
users[6] = "daryl"

fmt.Println("\n")

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

// Update value
users[6] = "michonne"

fmt.Println("\n")

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

//Access an Item
fmt.Println("\n", users[1], "\n")

//Remove an Item
delete(users, 3)

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

// Test if entry is present in the map or not
_, status := users[4]
fmt.Println("\n", status, "\n")
}

Output:

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example