본문 바로가기
Go

[Go] Map

by llHoYall 2021. 10. 21.

Map is a collection that accesses a value through a key.

In addition, map is a mutable, duplicable, and unordered data structure.

Map Declaration

var numMap1 map[string]int = make(map[string]int)
numMap1["one"] = 1
numMap1["two"] = 2
fmt.Println(numMap1)
// map[one:1 two:2]

numMap2 := make(map[int]string)
numMap2[1] = "one"
numMap2[2] = "two"
fmt.Println(numMap2)
// map[1:one 2:two

In Array and Slice, only integers can be used as index values, while Map can use all types of values as keys.

However, they should be of comparable type.

Specify the type of key in square brackets and the type of value on the outside.

Zero Initialization

As with Array and Slice, accessing keys on Map that do not assign any values returns zero values.

numMap := make(map[string]int)
fmt.Println(numMap["test"])
// 0

The zero values depend on the type of values.

 

As with Slice, the zero value of the Map variable itself is nil.

var nilMap map[string]string
fmt.Printf("%#v\n", nilMap)
// map[string]string(nil)

 

Map provides a method for distinguishing zero values from zero values assigned.

numMap := map[string]int{"one": 1, "two": 2}

value, isExist := numMap["one"]
fmt.Println(value, isExist)
// 1 true

value, isExist = numMap["three"]
fmt.Println(value, isExist)
// 0 false

Map Literal

medals := map[string]int{"bronze": 3, "silver": 2, "gold": 1}
fmt.Println(medals)
// map[bronze:3 gold:1 silver:2]

As you can see in the above example, Map doesn't have an order.

Delete Key-Value Pair

You can delete the k-v pair with Go's built-in function delete.

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

_, isExist := numMap["one"]
if isExist {
  delete(numMap, "one")
}

fmt.Println(numMap)
// map[three:3 two:2]

Map with Loop

Map use keys, while Array and Slice use indexes.

numMap := map[string]int{"one": 1, "two": 2, "three": 3}
for key, value := range numMap {
  fmt.Println(key, value)
}
// two 2
// three 3
// one 1

The print order can be changed each time you execute since Map is an unordered collection.

'Go' 카테고리의 다른 글

[Go] goroutine and channel  (0) 2021.10.23
[Go] Error Handling  (0) 2021.10.22
[Go] Linked List  (0) 2021.10.20
[Go] Functions  (0) 2021.10.19
[Go] Interface  (0) 2021.10.17

댓글