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:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example