Learn Go: 9. Built in set - map

Keywords: Go map

Learn what

  1. What is a map?

  2. How to create a map?

  3. Determine whether the key exists?

  4. How to get the map length?

  5. How to traverse a map?

  6. How to delete key / value pairs?

  7. Is map a reference type or a value type?

concept

map is an unordered set of key / value pairs, which is called dictionary, associative array, hash table and so on in other languages. When a key is given, it can quickly locate the value, and the key must be unique and cannot appear the same.

statement

Format: var variable name map [key type] [value type]

Example: a map with int key and string value is declared.

var dic map[int]string

Note: uninitialized, dic is nil.

Key type restrictions

When declaring a map, not all types of keys are supported, but only can be used= Or = = the type of operator to compare. Speaking this, I also understand that not all types can be compared in Go language.

Which types cannot be compared?

  • function

  • map

  • section

  • Elements are arrays of functions, map s, and slices

  • The field contains the structure of function, map and slice

initialization

There are two ways to initialize a map. The first is to use the make function. The second is to initialize specific keys and values when declaring a map. If the map is not initialized, the value cannot be accessed, otherwise the compiler will report an error.

1. make function

dic := make(map[int]string)

Now you can save the value. The initialized map will scale dynamically according to the new key value, and use the len function to obtain the length.

// collection/map-make.go

dic := make(map[int]string)

dic[1] = "lao"

dic[3] = "miao"

fmt.Println("dic length:", len(dic))

// output

dic length: 2

During initialization, you can define the required capacity (space size) of the map in advance. When the added key value exceeds the capacity, it will be automatically added by one.

// collection/map-make-cap.go

dic := make(map[int]string, 10)

// The capacity is 10 and 1 is saved

dic[1] = "lao"

fmt.Println("dic length:", len(dic))

// output

dic length: 1

2. Initialization upon declaration

A map with string key and int value is declared, and three key / value pairs are initialized.

// collection/map-init.go

m := map[string]int{

    "a": 2,

    "b": 3,

    "c": 4,

}

fmt.Println("b:", m["b"])

// output

b: 3

You can also not specify keys and values during initialization, which is the same as the make function without specifying capacity.

m := map[string]int{}

Equivalent to

m := make(map[string]int)

Does the key exist

When getting a key without storage from the initialized map, the compiler will not report an error, and it will return the default value of value type. For example, if the value type is int, it will return 0, and if the value type is string, it will return an empty string.

How do you determine whether the key exists? The format is as follows:

v,ok := map[key]
  • v: Value of map

  • ok: bool type. If the key exists, it is true; otherwise, it is false

give an example:

// collection/map-key.go

dic := map[int]string{}

dic[0] = "a"

if v, ok := dic[0]; ok {

    fmt.Println(v)

}

// output

a

Delete key / value pair

Use the delete function to delete key / value pairs in the map. The format is as follows:

delete(map, key)

Note: if the key does not exist, the compiler can also pass.

give an example:

m := map[string]int{

    "a": 2,

    "b": 3,

    "c": 4,

}

delete(m, "b")

fmt.Println(m)

// output

map[a:2 c:4]

ergodic

Traversing the map requires for range syntax. If you don't understand it, take a look first< Process control>.

m := map[string]int{

    "a": 2,

    "b": 3,

    "c": 4,

}

// k is the key and v is the value

for k, v := range m {

    fmt.Println("key:", k, ",value:", v)

}

// output

key: a ,value: 2

key: b ,value: 3

key: c ,value: 4

In the code, v can be omitted, which means that only the key is traversed. If you only want to traverse the value, k is replaced by (underscore), which means that it is omitted.

// Traverse keys only

for k := range m {

    ...

}

// Traversal values only

for _, v := range m {

    ...

}

reference type

map is a reference type, so it exists only once during the transfer process.

If it is like copying a map, there is no copy like function. The implementation needs to create a new map and manually traverse the assignment.

// collection/map-copy.go

m := map[string]int{

    "a": 2,

    "b": 3,

}

// Traversal copy

mCopy := map[string]int{}

for k, v := range m {

    mCopy[k] = v

}

summary

This article explains the creation, traversal, deletion and other knowledge points of map, which are very common, so we must master them.

Posted by hightechredneck on Tue, 28 Sep 2021 20:02:31 -0700