“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Write at the front 👀
Today I mainly talk about the Map of Go 🍩 the end of the semester is near, I should prepare for the exam, today is probably the last article of the year 😶
What is a Map 🍪
A Map is an unordered collection of key-value pairs 🎂
- Map features 🍰
- A map is a reference to a hash table
- Like slices, maps are reference types and cannot be assigned without initialization
- Go’s mapping syntax is similar to Python dictionaries and JSON in that it stores data as key-value pairs, and a value given a key can be quickly found
2. Map declaration and initialization assignment 🧁
1. Use the map keyword to declare map🍫
Keys and values are always one-to-one 🍭
- Grammar 👇
var mapname map[key_type] value_type
//key_type represents the key type (which must be comparable with ==), and value_type represents the value type
Copy the code
2. Initialize the map🍬 using the make() function
Map variables default to nil. They can be allocated memory using make(). Only non-nil maps can be assigned 🍡 directly
- Grammar 👇
make(map[key_type] value_type,cap)
//cap represents the map's capacity. This is an optional parameter, and len() can be used to return its capacity
Copy the code
- Sample 👇
/* Error example ❗*/
package main
import (
"fmt"
)
var Student map[int]string // Declare a map of key type int and value type string named Student
func main(a) {
fmt.Println(Student == nil)
Student[2103030105] = "Wang Yihui" Nil mappings cannot be assigned directly. The compiler will report an error
}
/* Correct example ✅*/
package main
import (
"fmt"
)
var Student map[int]string // Declare a map of key type int and value type string named Student
func main(a) {
Student = make(map[int]string) // Stufent is initialized with make()
fmt.Println(Student == nil) // The value is not nil
Student[2103030105] = "Wang Yihui"
fmt.Println(Student)
}
Copy the code
- Results 👇
3. Initialize 🍮 with map literal syntax
- Grammar 👇
Global initialization:var Student = map[int]string{
2103030105: "Wang Yihui".2103030106: "Li Zhihang".2103030107: "White New Handsome".2103030108: "Huang Fei Ming"} local initialization: Student :=map [int] string {
2103030105 : "Wang Yihui" ,
2103030106 : "Li Zhihang" ,
2103030107 : "White New Handsome" ,
2103030108 : "Huang Fei Ming",}Copy the code
3. Basic usage of map 🍯
1. Add 🍼
- Sample 👇
package main
import "fmt"
var Student = map[int]string{
2103030105: "Wang Yihui".2103030106: "Li Zhihang".2103030107: "White New Handsome".2103030108: "Huang Fei Ming",}func main(a) {
/* Add two students to Student */
Student[2103030109] = "Xu Xiangyu"
Student[2103030110] = "Sun Qingkun"
fmt.Println(Student)
}
Copy the code
- Results 👇
2. Delete 🥛
Use the delete(map, key) function to delete a group of key-value pairs, where map is the map instance to be deleted and key is the key of key-value pairs in the map to be deleted
- Sample 👇
delete(Student, 2103030105) // delete student id 2103030105
Copy the code
- Results 👇
3. 🧃 instead
- Sample 👇
Student[2103030106] = Bighorn bull// Change student id 2103030106 to bighorn
Copy the code
- Results 👇
4. Check ☕
(1) Use for range to traverse map🍵
- Sample 👇
package main
import "fmt"
var Student = map[int]string{
2103030105: "Wang Yihui".2103030106: "Li Zhihang".2103030107: "White New Handsome".2103030108: "Huang Fei Ming",}func main(a) {
/* Add two students to Student */
Student[2103030109] = "Xu Xiangyu"
Student[2103030110] = "Sun Qingkun"
delete(Student, 2103030105) // delete student id 2103030105
Student[2103030106] = Bighorn bull // Change student id 2103030106 to bighorn
/*number represents the key, and name represents the value. If only the value is needed, you can use the anonymous variable _ instead of the number position */
for number, name := range Student {
fmt.Printf("Student ID: %d Name: %s\n", number, name)
}
}
Copy the code
- Results 👇
(2) Determine whether a key exists 🧉
In go, there is a special blood method to determine whether a map key exists. The format is 👇
value,ok:=map[key]
Copy the code
- Map indicates the map name and key indicates the key to be searched
- Ok returns a bool
- If OK is true, value returns the value of the key; If OK is false, the default value for the map value type is returned
- Sample 👇
/* Find if student id is 2103030105 */
name, ok := Student[2103030105]
if ok {
fmt.Printf("%s\n", name) // If yes, print the student's name
} else {
fmt.Printf("No one! \n") // If there is no such person in the database, it is not found in the database.
}
Copy the code
- Results 👇
4. Traverse the map in sequence 🍶
The order in which the map is traversed is independent of the order in which the key-value pairs are added, because the traversal order is random 🍾
If you want to sort a map in the specified order, you can first save the map’s keys into the slice and then introduce a sort package
- if
The key is an integer
Create a slice of type int using sort packageInts()
Function to sort the slices, then use range to traverse the key slices, then useThe map [key] way
The output value - if
Key is a string
Create a string slice using sort packageStrings()
Function to sort slices, in traversing key slices through range, withThe map [key] way
The output value
- Sample 👇
package main
import (
"fmt"
"sort"
)
var Student = map[int]string{
2103030106: "Li Zhihang".2103030105: "Wang Yihui".2103030108: "Huang Fei Ming".2103030107: "White New Handsome",}func main(a) {
// Create a section of type int to store the key.
slice_student := make([]int.0.10)
// Use the for range loop and the append function to store the student number into the slice
for number := range Student {
slice_student = append(slice_student, number)
}
sort.Ints(slice_student) // Sort student numbers
// Output value by key
for _, key := range slice_student {
fmt.Printf("Student ID: %d Name: %s\n", key, Student[key])
}
}
Copy the code
- Results 👇
5. Hybrid Map 🍷
1. The value is map🍸
package main
import "fmt"
var Student = map[int]map[string]int{
2103030106: {"Li Zhihang":18},
2103030105: {"Wang Yihui":19},
2103030108: {"Huang Fei Ming":19},
2103030107: {"White New Handsome":17}},func main(a) {
fmt.Println(Student)
}
Copy the code
2. Map of the slice type 🍹
- Sample 👇
package main
import "fmt"
var QinLi_Studio = map[string] []string{
"Front-end team member": {"Song Juntang"."Wang"."Li Wanyang"},
"Back-end group member": {"Li Zhihang"."提闯"."Zou Liying"},
"O&m Team member": {"Gao Qing Han"."Li Chuang"."Liang Xiaoyu"}},func main(a) {
fmt.Println(QinLi_Studio)
}
Copy the code
- Results 👇
3. Slice 🍺 whose element type is Map
- Sample 👇
package main
import "fmt"
// Initialize the slice
var Student = make([]map[string]string.2.100)
func main(a) {
Student[0] = make(map[string]string.10) // Initialize the map element in the slice
Student[0] ["Name"] = "Li Zhihang"
Student[0] ["Student id"] = "2103030106"
Student[0] ["Native"] = "Quzhou"
Student[1] = make(map[string]string.10) // Initialize the map element in the slice
Student[1] ["Name"] = "White New Handsome"
Student[1] ["Student id"] = "2103030107"
Student[1] ["Native"] = "Dalian"
fmt.Println(Student)
}
Copy the code
- Results 👇
Write it at the back 🍻
Thank you for watching ✨ my 14 days more text challenge successfully 🥂 thanks to the nuggets operation students, review hard 💗
PS: What deficiencies, welcome to point out oh 💖