Go language introduction series (IV) the use of map


Previous articles in this series:

  • Go language introduction series (I) installation and use of go
  • Basic grammar summary of go language introduction series (2)
  • Go language introduction series (3) arrays and slices

1. Declaration

A map is a map that allows you to(key)Map to value(value), in the format:map[keyType]valueType

Declare a map and initialize it, usingkey:valueTo initialize:

Var scores = map [string] int {"Mathematics": 100, "Chinese": 90, "go": 100}

If you don’t want to initialize directly, you can declare it before using it. Note that it needs to be usedmakeFunction can only be used after initialization:

var scores map[string]int
scores = make(map[string]int)

Why does this declaration need to be usedmakeFunction?

mapThe zero value of isnil map, there are no keys and keys cannot be added.

Var m map [string] int // declares an M map, which is now nil by default
fmt.Println(m) //map[]
M ["a"] = 1 // an error is reported: assignment to entry in nil map

So in order not to let themapnonil, need to usemakeinitialization:

var m map[string]int //nil
M = make (map [string] int) // initialization
M ["a"] = 1 // add element
fmt.Println(m) //map[A:1]

Of course, the convenient short variable declaration method can also be used:

m := map[string]int {"A":1, "B":2}
m := make(map[string]int)
m["A"] = 1
m["B"] = 2

2. Addition, deletion, modification and query

(add) add key value pair:

Scores ["math"] = 100 // data with the key "math" and the value of 100 is added to the scores map
Scores ["Chinese"] = 90

(delete) delete key value pairs:

Delete (scores, "Chinese")

(change) the syntax of modifying key value pairs and adding key value pairs is the same (whenkeyIt is increased when it does not existkeyModify when existing):

Scores ["Chinese"] = 10

(check) usekeyYou can find the correspondingvalue, two values will be returned, the first iskeyCorrespondingvalue, the second is a Boolean value ifkeyExistence, yestrue; Otherwisefalse)。 If foundkeyDoes not exist, returnsvalueZero value of type:

Score, exist: = scores ["math"] // use two return values
fmt.Println(score, exist) //100 true

Score1: = scores [language] // use a return value
fmt.Println(score1) //90

Score2, exist2: = scores ["Java"] // find a nonexistent key
fmt.Println(score2, exist2) //0 false

3. Other usage

andsliceLike,mapIt is also a reference type, which means that if there are severalmapPoint to an underlying layer at the same timemap, one of themmapIf you change a key value pair, others will make the same change (because the underlyingmapChanged).

package main

import "fmt"

func main() {
	Map0: = make (map [string] string) // bottom Map0
	Map0 ["name"] = "xingxiaoguan" // add a key value pair

	//MAP1 MAP2 refers to Map0
	map1 := map0
	map2 := map0

	FMT. Println (Map0 ["name"], MAP1 ["name"], MAP2 ["name"] // all are xingxiaoguan

	MAP1 ["name"] = "xingrenguanxue" // change the value corresponding to MAP1's name
	FMT. Println (Map0 ["name"], MAP1 ["name"], MAP2 ["name"] // all become xingrenguanxue

uselenFunction can getmapinkeyQuantity of:

Keynum: = len (scores) // get the number of keys in the score map

mapIs unordered, so the order of elements returned may be different each time.

have access torangeKeyword traversalmap, hererangeThe first value returned iskey, the second value isvalue

//Traverse scores map
for key, value := range scores {
    fmt.Println(key, value)

Math 100
Chinese 90

Please correct any errors.

4. About me

Click here to meet me. (^o^)/