[Golang] Map

2021-11-29 hit count image

Let's see how to define and use Map that is one of the data structure in Golang.

Outline

In this blog post, I will show you how to define and use Map in Golang. You can see the full source code of this blog post on the link below.

Map

The Map is a data structure that stores the data in the key-value. Depending on the programming language, it is called a dictionary, a hash table, or a has map.

In Golang, you can define the app like the below.

// map[KEY_TYPE]VALUE_TYPE
map[string]int

And you can use the make function to define the variable like the below.

m := make(map[string]string)

To check this, create a main.go file and modify it like the below.

package main

import "fmt"

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

  m["name"] = "John"
  m["country"] = "Korea"
  fmt.Println(m)

  m["city"] = "Seoul"
  fmt.Println(m)

  fmt.Printf("No key: %s / %T\n", m["language"], m["language"])
}

When you run the above code, you will get the result like the below.

# go run main.go
map[country:Korea name:John]
map[city:Seoul country:Korea name:John]
No key:  / string

If you try to access the key that doesn’t exist in the map, the default value of the value’s type is returned. In above example, you can see the `` that is a default value of the string type.

Check key exists

If you access the key that doesn’t exist in the map, the default value of the value’s type is returned. So, if you store the default value of the type in the map like the below, how can you know the value was assigned or unassigned?

package main

import "fmt"

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

  m["name"] = ""
  fmt.Printf("name: %s / %T\n", m["name"], m["name"])
  fmt.Printf("country: %s / %T\n", m["country"], m["country"])
}

For this issue in Golang, when you sue a key to get a value from the map, it also returns whether the key value exists in the map.

v, ok := m["name"]

If the key exists in the map, the ok variable is set to true, if not, it is false.

To check this, modify the main.go file like the below.

package main

import "fmt"

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

  m["name"] = ""
  fmt.Printf("name: %s / %T\n", m["name"], m["name"])
  fmt.Printf("country: %s / %T\n", m["country"], m["country"])

  v, ok := m["name"]
  fmt.Println(v, ok)

  v, ok = m["country"]
  fmt.Println(v, ok)
}

When the code is executed, you will get the result like the below.

# go run main.go
name:  / string
country:  / string
 true
 false

This allows us to check whether the key exists in the map or not.

Delete element

In Golang, you can use the delete function like the below to remove the element in the map.

delete(MAP_VARIABLE, KEY)

To check this, modify the main.go file like the below.

package main

import "fmt"

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

  m[1] = 0
  m[2] = 2
  m[3] = 3

  v, ok := m[1]
  fmt.Println(v, ok)

  delete(m, 1)

  v, ok = m[1]
  fmt.Println(v, ok)
}

When the code is executed, you will get the result like the below.

# go run main.go
0 true
0 false

Before deleting the element by the delete function, the value corresponding to the key is 0. And after deleting the element, you can see the value is still 0.

After deleting the element, the 0 is returned because the key doesn’t exists in the map and the default value of the int type is returned. So, if you just check the value, you don’t know the value was assigned or unassigned.

Therefore, it’s better to use the second variable(ok) to check whether the key exists in the map or not.

Iterate map

You can use the for statement with the range like the below to access all key/value in the map.

m := make(map[int]int)

for key, value := range m {
  fmt.Println(key, value)
}

To check this, modify the main.go file like the below.

package main

import "fmt"

type Product struct {
  Name  string
  Price int
}

func main() {
  m := make(map[int]Product)

  m[19] = Product{Name: "TV", Price: 3000}
  m[16] = Product{Name: "Phone", Price: 1000}
  m[18] = Product{Name: "PC", Price: 500}
  m[17] = Product{Name: "Tablet", Price: 2000}

  for key, value := range m {
    fmt.Println(key, value)
  }
}

When you run the above code, you will get the result like the below.

# go run main.go
18 {PC 500}
17 {Tablet 2000}
19 {TV 3000}
16 {Phone 1000}

Golang uses the hash map, so the order of the key/value is not guaranteed.

  • Hash map: unsorted map
  • Sorted map: sorted map

Compare map, array, list

The result below is the comparison of the map, array, and list in the Big-O notation.

ActionArray, SliceListMap
AddO(N)O(1)O(1)
DeleteO(N)O(1)O(1)
ReadO(1)O(N)O(1)

The map has a good performance in adding, deleteing, and reading in O(1), but the order is not guaranteed in the for statement, and it uses a lot of memory.

If you want to know the Big-O notation, see the previous blog post.

Completed

Done! we’ve seen how to define the map and how to use it in Golang. If you want to know other data structures in Golang like the list, queue, stack, ring, see the link below.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts