当前位置:网站首页>go map

go map

2022-04-23 20:39:00 baboon_ chen

go map characteristic

1、map Normal operation .

Map Stored is an unordered collection of key value pairs , lead ⽤ type , Hashtable . The key has to be ⽀ Hold the equality operator (==、!=) type ,⽐ Such as number、string、pointer、array、struct, And corresponding interface. Values can be any type , There is no limit to .

Example :

unc test1() {
    
	// 1、 initialization 
	m1 := make(map[int]string, 1000)	// 1000 Express map Maximum storage key_value The number of , Beyond , Need to reallocate memory 

	m2 := map[string]int{
    
		"a": 1,
	}

	// 2、 Judge  key  Whether there is 
	if val, ok := m2["a"]; ok {
    
		fmt.Println(val)
	}

	// 3、 Access does not exist key
	fmt.Println(m2["b"]) //  return value Default initial value of type 

	// 4、 Add or modify 
	m2["b"] = 1

	// 5、 Delete key
	delete(m2, "c") //  If key non-existent , No mistakes 

	// 6、 Get the number of key value pairs 
	fmt.Println(len(m1)) // cap Invalid 

	// 7、 Traverse 
	for k, v := range m2 {
    
		fmt.Println(k, v) //  Return in random order , It's different every time 
	}

	for k := range m2 {
    
		fmt.Println(k)
	}

	for _, v := range m2 {
    
		fmt.Println(v)
	}

}

2、 How to traverse in sequence map? take key Sort , And then according to key Go find value.

Example :

func test2() {
    
	m := make(map[string]int, 32)
	rand.Seed(time.Now().UnixNano())
	keySlice := []string{
    }

	for i := 0; i < 10; i++ {
    
		key := fmt.Sprintf("stu_%d", i)
		m[key] = rand.Intn(100)
		keySlice = append(keySlice, key)
	}

	fmt.Println("before sort, the map is:")
	for k, v := range m {
    
		fmt.Println(k, v)
	}

	fmt.Println("\nafter sort:")
	sort.Strings(keySlice)
	for _, v := range keySlice {
    
		fmt.Println(v, m[v])
	}
}

Output :

before sort, the map is:
stu_3 99
stu_4 34
stu_6 9
stu_9 92
stu_2 37
stu_8 92
stu_7 79
stu_0 88
stu_5 41
stu_1 69

after sort:
stu_0 88
stu_1 69
stu_2 37
stu_3 99
stu_4 34
stu_5 41
stu_6 9
stu_7 79
stu_8 92
stu_9 92

3、 from map What is retrieved from the is ⼀ individual value Temporary copy , Changes to its members are meaningless .

Example :

type user struct{
     name string }
m := map[int]user{
            //  When  map  Due to expansion ⽽ When hashing again , The storage location of each key value item will send ⽣ change . therefore ,map
    1: {
    "user1"},         //  Designed to  not addressable. similar  m[1].name  This expectation passes through the original  value
}                         //  Pointer to modify the name of the member ⾏ by ⾃ However, it will be banned ⽌.
m[1].name = "Tom"         // Error: cannot assign to m[1].name

Correct modification method :

//  Method 1
u := m[1]				// m[1] Returns the structure of a value copy 
u.name = "Tom"
m[1] = u                  //  Replace  value.

//  Method 2
m2 := map[int]*user{
    	 // m2[1] Return pointer copy 
    1: &user{
    "user1"},
}
m2[1].name = "Jack"       //  Returns a copy of the pointer . It is allowed to modify the original object through the pointer .

4、 You can safely delete key values during iteration . However, if there are new operations during the period , There will be an exception .

Example :

func test3() {
    
	m := map[int]string{
    
		1: "zhou",
		2: "wu",
		3: "zheng",
		4: "wang",
	}
	fmt.Printf("before delete, the map is:%v\n", m)
	for k := range m {
    
		delete(m, k)
	}
	fmt.Printf("after delete, the map is:%v\n", m)

	m2 := map[int]string{
    
		1: "zhou",
		2: "wu",
		3: "zheng",
		4: "wang",
	}
	fmt.Printf("\nbefore delete, the m2 is:%v\n", m2)
	for k := range m2 {
    
		m2[k+k] = "add new"
		delete(m2, k)
	}
	fmt.Printf("after delete, the m2 is:%v\n", m2)
}

Output :

before delete, the map is:map[1:zhou 2:wu 3:zheng 4:wang]
after delete, the map is:map[]

before delete, the m2 is:map[1:zhou 2:wu 3:zheng 4:wang]
after delete, the m2 is:map[4:add new 6:add new 16:add new]

5、 map_slice、 slice_map

Example :


func sliceMap() {
    
	s := make([]map[string]int, 4)
	s[0] = make(map[string]int, 16)
	s[0]["stu_01"] = 50
	s[0]["stu_02"] = 60
	s[0]["stu_01"] = 70

	for i, v := range s {
    
		fmt.Printf("s[%d] = %#v\n", i, v)
	}
}

func mapSlice() {
    
	m := make(map[string][]int, 4)
	key := "stu_01"
	if _, ok := m[key]; !ok {
    
		m[key] = make([]int, 0, 8)
	}

	m[key] = append(m[key], 100)
	m[key] = append(m[key], 200)
	m[key] = append(m[key], 300)

	for k, v := range m {
    
		fmt.Println(k, v)
	}
}

Output :

s[0] = map[string]int{
    "stu_01":70, "stu_02":60}
s[1] = map[string]int(nil)
s[2] = map[string]int(nil)
s[3] = map[string]int(nil)
stu_01 [100 200 300]

版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351399.html