This is the 9th day of my participation in the August Wen Challenge.More challenges in August

Map

Map is a reference type

Each element consists of a key and a value, which is an unordered collection of keys: values

Define the format

var m map[keyType]valueType

KeyType: must be a comparable type, such as int, float, string

ValueType: The value can be of any type. ValueType can be declared as an empty interface type, interface{}, and this value can hold any value

The map to create

Declare a map with a value of nil

Var m0 map[string]int panic when adding elements to a nil map, panic occurs // m0["shaosiming"] = 18 FMT.Printf("%#v \n", m0)Copy the code

Define a map and initialize it to null

M1 ["tianming"] = 18 FMT.Println(m1);Copy the code

When creating a map, initialize data

Var m2 = map[string]int{"shaosiming":18, "dashiming":20} FMT.Println(m2)Copy the code

Use make to create a map

// make(map[string]float64) // This empty map can also add data m3["ThreeBody"] = 88.8 m3["EasyLove"] = 66.6 Println("m3 length: ", len(m3)) fmt.Printf("%#v \n", m3) // make(map[string]int, 10) fmt.Println("m4: ", len(m4)) fmt.Printf("%#v \n", m4)Copy the code

Note: Map in Go is a reference type. When we only declare a map, we do not initialize it, pointing to nil. When we add data to such a map, panic will occur

The map of access

Access directly through the key

M5 := make(map[string]string, 10) m5["shaosiming"] = "like blue buff" m5["dasiming"] = "like red buff" fmt.Println(m5["shaosiming"]) Println(m5["dasiming"]) // If the key is in the map, return true, otherwise return false */ v, ok := m5["shaosiming2"] if ok { fmt.Println(v) } else { fmt.Println("this key shaosiming no exist") }Copy the code

Access through the range statement

Println("key: = range m5 {FMT.Println("key: = range m5 {FMT.Println("key: = range m5 {FMT.Println("key: = range m5 {FMT. ", key, "value:", m5[key])} // If the first value is key, the second value is value for key, value: = range m5 {fmt.Println("key: ", key, "value:", value) }Copy the code

Update data in the map

// Add this data if there is no such key in the map. If there is such key, update value m5["shaosiming"] = "daozhi" ftt.println (m5)Copy the code

Delete data from the map

/* delete(m5, "shaosiming")Copy the code

Sequential access to the map

/ / the map of sequential access m6: = make (map (int) string, 5) m6 [0] = "a" m6 [1] = "b" m6 [2] = "c" m6 [3] = "d" m6 [4] = "e" for k, v := range m6 { fmt.Println("key: ", k, "value: Printf("%#v \n", m6) var idxs []int for k := range m6 {idxs = append(idxs, m6) Println(idxs) Println(idxs) Println(idxs) Println(idxs) idx := range idxs { fmt.Println("key: ", idx, "value: ", m6[idx]) }Copy the code