Shubham Ankit

Shubham Ankit

1578472935

Introduction to Golang Maps With Examples

A map is a data structure that provides you with an unordered collection of key/value pairs (maps are also sometimes called associative arrays in Php, hash tables in Java, or dictionaries in Python). Maps are used to look up a value by its associated key. You store values into the map based on a key.

The strength of a map is its ability to retrieve data quickly based on the key. A key works like an index, pointing to the value you associate with that key.

A map is implemented using a hash table, which is providing faster lookups on the data element and you can easily retrieve a value by providing the key. Maps are unordered collections, and there’s no way to predict the order in which the key/value pairs will be returned. Every iteration over a map could return a different order.

Go provides a built-in map type. In this article, we’ll learn how to use Golang’s built-in map type.

Declaring a map in Golang

A Go map type looks like the following.

syntax

var m map[KeyType]ValueType


where KeyType may be any comparable type (more on this later), and ValueType may be any type at all, including another map.

See the variable m is a map of string keys to int values.

var m map[string]int


Map types are reference types, like pointers or slices, and so the value of m above is nil.

A nil map has no keys. A nil map behaves like a blank map when reading. Any attempt to add keys to a nil map will result in a runtime error.

See the below code of nil variable in Go.

// hello.go

package main

import "fmt"

func main() {
    var app map[string]int
    fmt.Println(app)
    if app == nil {
        fmt.Println("app variable is nil")
    }
}

See the below output.

This is image title

Now, let’s add the items to the nil map and see the output.

// hello.go

package main

import "fmt"

func main() {
    var app map[string]int
    app["dividend"] = 21
    fmt.Println(app)
}

Output

This is image title

It is, therefore, necessary to initialize a map before adding items to it.

Initializing a map

1. Initializing a map using the built-in make() function

You can initialize a map using the built-in make() function. You just need to pass the type of the map to the make() function as in the example below. The function will return an initialized and ready to use map -

// Initializing a map using the built-in make() function
var m = make(map[string]int)

Let’s see a complete example -

package main
import "fmt"

func main() {
	var m = make(map[string]int)

	fmt.Println(m)

	if m == nil {
		fmt.Println("m is nil")
	} else {
		fmt.Println("m is not nil")
	}

	// make() function returns an initialized and ready to use map.
	// Since it is initialized, you can add new keys to it.
	m["one hundred"] = 100
	fmt.Println(m)
}

Output

map[]
m is not nil
map[one hundred:100]

2. Initializing a map using a map literal

A map literal is a very convenient way to initialize a map with some data. You just need to pass the key-value pairs separated by colon inside curly braces like this -

var m = map[string]int{
	"one": 1,
	"two": 2,
	"three": 3,
}

Note that the last trailing comma is necessary, otherwise, you’ll get a compiler error.

Let’s check out a complete example -


package main
import "fmt"

func main() {
	var m = map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
		"four":  4,
		"five":  5, // Comma is necessary
	}

	fmt.Println(m)
}

Output

map[one:1 two:2 three:3 four:4 five:5]


You can also create an empty map using a map literal by leaving the curly braces empty -

// Initialize an empty map
var m = map[string]int{}

The above statement is functionally identical to using the make() function.

Adding items (key-value pairs) to a map

You can add new items to an initialized map using the following syntax -

m[key] = value

The following example initializes a map using the make() function and adds some new items to it -

package main
import "fmt"

func main() {
	// Initializing a map
	var tinderMatch = make(map[string]string)

	// Adding keys to a map
	tinderMatch["Rajeev"] = "Nano" // Assigns the value "Nano" to the key "Rajeev"
	tinderMatch["Jack"] = "Sophia"
	tinderMatch["David"] = "Tina"

	fmt.Println(tinderMatch)

	/*
	  Adding a key that already exists will simply override
	  the existing key with the new value
	*/
	tinderMatch["Rajeev"] = "Jony"
	fmt.Println(tinderMatch)
}

Output


map[Rajeev:Nano Jack:Sophia David:Tina]
map[Rajeev:Jony Jack:Sophia David:Tina]

If you try to add a key that already exists in the map, then it will simply be overridden by the new value.

Retrieving the value associated with a given key in a map

You can retrieve the value assigned to a key in a map using the syntax m[key]. If the key exists in the map, you’ll get the assigned value. Otherwise, you’ll get the zero value of the map’s value type.

Let’s check out an example to understand this -

package main
import "fmt"

func main() {
	var personMobileNo = map[string]string{
		"John":  "+33-8273658526",
		"Steve": "+1-8579822345",
		"David": "+44-9462834443",
	}

	var mobileNo = personMobileNo["Steve"]
	fmt.Println("Steve's Mobile No : ", mobileNo)

	// If a key doesn't exist in the map, we get the zero value of the value type
	mobileNo = personMobileNo["Jack"]
	fmt.Println("Jack's Mobile No : ", mobileNo)
}

Output

Steve's Mobile No :  +1-8579822345
Jack's Mobile No : 

In the above example, since the key "Jack" doesn’t exist in the map, we get the zero value of the map’s value type. Since the map’s value type is string, we get " ".

Unlike other languages, we do not get a runtime error in Golang if the key doesn’t exist in the map.

But what if you want to check for the existence of a key? In the above example, the map would return " " even if the key "Jack" existed with the value " ". So how do we distinguish between cases where a key exists with the value equal to the zero value of the value type, and the absence of a key?

Well, let’s find out.

Checking if a key exists in a map

When you retrieve the value assigned to a given key using the syntax map[key], it returns an additional boolean value as well which is true if the key exists in the map, and false if it doesn’t exist.

So you can check for the existence of a key in a map by using the following two-value assignment

value, ok := m[key]


The boolean variable ok will be true if the key exists, and false otherwise.

Consider the following map for example. It maps employeeIds to names -

var employees = map[int]string{
	1001: "Rajeev",
	1002: "Sachin",
	1003: "James",
}

Accessing the key 1001 will return "Rajeev" and true, since the key 1001 exists in the map -

name, ok := employees[1001]  // "Rajeev", true


However, If you try to access a key that doesn’t exist, then the map will return an empty string "" (zero value of strings), and false -


name, ok := employees[1010]  // "", false

If you just want to check for the existence of a key without retrieving the value associated with that key, then you can use an _ (underscore) in place of the first value -

_, ok := employees[1005]


Now let’s check out a complete example


package main
import "fmt"

func main() {
	var employees = map[int]string{
		1001: "John",
		1002: "Steve",
		1003: "Maria",
	}

	printEmployee(employees, 1001)
	printEmployee(employees, 1010)

	if isEmployeeExists(employees, 1002) {
		fmt.Println("EmployeeId 1002 found")
	}
}

func printEmployee(employees map[int]string, employeeId int) {
	if name, ok := employees[employeeId]; ok {
		fmt.Printf("name = %s, ok = %v\n", name, ok)
	} else {
		fmt.Printf("EmployeeId %d not found\n", employeeId)
	}
}

func isEmployeeExists(employees map[int]string, employeeId int) bool {
	_, ok := employees[employeeId]
	return ok
}

Output

name = Rajeev, ok = true
EmployeeId 1010 not found
EmployeeId 1002 found

In the above example, I’ve used a short declaration in the if statement to initialize the name and ok values, and then test the boolean value ok. It makes the code more concise.

Deleting a key from a map

You can delete a key from a map using the built-in delete() function. The syntax looks like this -

// Delete the `key` from the `map`
delete(map, key)

The delete() function doesn’t return any value. Also, it doesn’t do anything if the key doesn’t exist in the map.

Here is a complete example


package main

import "fmt"

func main() {
	var fileExtensions = map[string]string{
		"Python": ".py",
		"C++":    ".cpp",
		"Java":   ".java",
		"Golang": ".go",
		"Kotlin": ".kt",
	}

	fmt.Println(fileExtensions)

	delete(fileExtensions, "Kotlin")

	// delete function doesn't do anything if the key doesn't exist
	delete(fileExtensions, "Javascript")

	fmt.Println(fileExtensions)
}

Output

map[Python:.py C++:.cpp Java:.java Golang:.go Kotlin:.kt]
map[Python:.py C++:.cpp Java:.java Golang:.go]

Maps are reference types

Maps are reference types. When you assign a map to a new variable, they both refer to the same underlying data structure. Therefore changes done by one variable will be visible to the other -

package main
import "fmt"

func main() {
	var m1 = map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
		"four":  4,
		"five":  5,
	}

	var m2 = m1
	fmt.Println("m1 = ", m1)
	fmt.Println("m2 = ", m2)

	m2["ten"] = 10
	fmt.Println("\nm1 = ", m1)
	fmt.Println("m2 = ", m2)
}


Output

m1 =  map[one:1 two:2 three:3 four:4 five:5]
m2 =  map[one:1 two:2 three:3 four:4 five:5]

m1 =  map[one:1 two:2 three:3 four:4 five:5 ten:10]
m2 =  map[one:1 two:2 three:3 four:4 five:5 ten:10]


The same concept applies when you pass a map to a function. Any changes done to the map inside the function is also visible to the caller.

Iterating over a map

You can iterate over a map using range form of the for loop. It gives you the key, value pair in every iteration -

package main
import "fmt"

func main() {
	var personAge = map[string]int{
		"Rajeev": 25,
		"James":  32,
		"Sarah":  29,
	}

	for name, age := range personAge {
		fmt.Println(name, age)
	}

}

Output

James 32
Sarah 29
Rajeev 25

Note that, A map is an unordered collection and therefore the iteration order of a map is not guaranteed to be the same every time you iterate over it.

So if you run the above program multiple times, you’ll get the results in different orders.
The article ends here,Thanks for reading !

Learn More

#go #golang

What is GEEK

Buddha Community

Introduction to Golang Maps With Examples
Ly  Jangi

Ly Jangi

1601282177

Working with Golang Maps

Maps (also called dictionaries) are a very useful tool in helping to store and organize objects to be accessed in an efficient method. Most basic implementations of a map involve using a key to access a value in the map, resulting in key-value pairs, in which one key is associated with a specific value in the map. Within Go, maps follow this definition. This blog will cover the basic use cases of maps in Go, and how a newcomer to the language may utilize them for their applications.

Initialization

Initialization of a map can be done using the make command. This is similar to the initialization of a slice:

mapObject := make(map[string]string)

In this case, mapObject is a map that uses strings as a key to map to another string. When creating a map, the key type must be a type that is Comparable, or more specifically types that can be compared using the == operator. Examples of valid key types include booleans, numbers, strings and several other primitives can be used as keys. For reference on types, check out this link. One extra thing to note is that structs can be used as a key, provided that all the properties of the struct are Comparable.

#go #maps #golang #golang maps

Neal  Bode

Neal Bode

1599287768

Golang Map Example | Maps in Go Tutorial Explained

Golang map is an inbuilt data type that has keys that are unique within the map while the values may or may not be the same. The map data structure in Golang is used for fast lookups, retrieval, and deletion of the data based on keys; that is why it is one of the most used data structures in computer science. Go map is an unordered collection of key-value pairs. They map keys to values.

Golang Map Example

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general, they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

Go provides another essential data type named the map which maps unique keys to values. A key is an object that you use to retrieve the value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

There are also other data types available unlike maps for example  arrays,  structs, and  slice in Golang. Let’s start our Golang maps tutorial.

#golang #go #golang map

Hire Dedicated Golang Developers | Golang Web Development Company

Does your business need a robust system across large-scale network servers then developing your app with a Golang programming language is the way to go. Golang is generally used for the development of highly secured, High Speed and High Modularity apps such as a FinTech Industry.

Want to develop a Highly secured app for your business?

Then hire a dedicated Golang developer from WebClues Infotech that are highly skilled in carrying out the work in a timely and qualitative output. With WebClues Infotech you get the assurance that we know what are the customers’ expectations and how to deliver on them on time.

Get your desired Golang Developer based on your project requirement!!

Share your requirements here https://www.webcluesinfotech.com/contact-us/

Book Free Interview with Golang developer: https://bit.ly/3dDShFg

#hire golang developer #hire go language developer #dedicated golang app developers #golang web development company #hire golang developers india #hire expert golang developers

Golang maps | Iterating over a Map | Golang Tutorial for Beginners

Iterating Over a Map.
You can iterate over a map using “range” form of the for loop. Its gives the key , value pair in every Iteration.
Map is an unordered collection and therefore iteration order of a map is not guaranteed over to be same every time we iterate.
Let me know if you have any questions in Maps.

#golang #iteration #maps #golangbasics #golangforbeginners

#golang #maps #go