[Go] Language Learning (f) map

map

map is based on a disordered key-valuedata structure, Go language map and slices are reference types, it must be initialized before use .

map definitions

Go language  mapsyntax defined as follows:

map[KeyType]ValueType

among them,

  • KeyType: indicates the type of bond.
  • ValueType: represents the type of the value corresponding to the key.

map type variable default initial value is nil, need to use the make () function to allocate memory . The syntax is:

make(map[KeyType]ValueType, [cap])

Where the cap represents the map capacity, although this parameter is not required, but we should assign it an appropriate capacity when you initialize the map .

Basic use map

The map data is occurring in pairs, the basic map sample code is as follows:

/* 创建map,并初始化 */
	var m1 map[string]int
	fmt.Println(m1 == nil)        //true:还没有初始化(没有在内存中开辟空间)
	m1 = make(map[string]int, 10) //估算好map的容量,避免在程序运行期间在动态扩容
	m1["李子健"] = 100
	m1["lizijian"] = 10
	fmt.Println(m1)

Output:

true
map[lizijian:10 李子健:100]

map also supports filling element when it was declared , for example:

func main() {
	userInfo := map[string]string{
		"username": "李子健",
		"password": "123456",
	}
	fmt.Println(userInfo) //
}

To fetch the map data

/* 向map中取数据,(会返回两个值,value和ok一起接受)
	   约定熟成用ok接受返回的bool值 */
	value, ok := m1["李子健"]

	if !ok {
		fmt.Println("查无此key")
	} else {
		fmt.Println(value)
	}

map traversal

Go language used for rangeto traverse map.

/* 遍历map值 */
	for key, value := range m1 {
		fmt.Println(key, value)
	}

Note:  the elements when traversing the map regardless of the order in order to add key-value pairs.

Use delete () function to remove key-value pairs

Use delete()the built-in function to remove the key from the map a set of pairs delete()formatting functions as follows:

delete(map, key)

among them,

  • map: you delete key-value pairs map
  • key: the key to be deleted represents key-value pairs

Sample code is as follows:

/* 删除map */
	delete(m1, "lizijian")
	delete(m1, "lijiayang") //删除不存在的值不报错
	fmt.Println(m1)

Traversal order specified map

/* 按照指定的key值顺序取出值 */

	m2 := make(map[string]int, 100)
	// 生成一个随机的map
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("stu%02d", i) //比较重要
		value := rand.Intn(100)
		m2[key] = value
	}
	fmt.Println(m2)
	//用一个切片keys去存储map中所有的key值
	var keys = make([]string, 0, 200)
	for key := range m2 {
		keys = append(keys, key)
	}
	//对切片进行排序
	sort.Strings(keys)

 	//通过排好序的keys中的key去遍历map
	for _, key := range keys {
		fmt.Println(key, m2[key])
	} 

Type of map elements sliced

The following code shows the operation of element sections when a map type:

/* 元素为map类型的切片 */
	mapslice := make([]map[int]string, 10, 10)
        //初始化一个类型为map的切片
	for i, v := range mapslice {
		fmt.Println(i, v)
	}

	//对切片中的map元素进行初始化
	mapslice[0] = make(map[int]string, 10)
	mapslice[0][1] = "小王子"
	for index, value := range mapslice {
		fmt.Println(index, value)
	}

Note: slice and map are reference types, use of time is required to initialize

Slice type values ​​map

The following code shows the map value slice types of actions:

    /*值为切片类型的操作:*/
	sliceMap:=make(map[string][]int,10)
	value1:=make([]int,10,10)//很重要
	sliceMap["李子健"]=value1//很重要
	for key,value:=range sliceMap{
		fmt.Println(key,value)
	}

Note the difference between new and make the

Let's look at an example:

func main() {
	var a *int
	*a = 100
	fmt.Println(*a)

	var b map[string]int
	b["沙河娜扎"] = 100
	fmt.Println(b)
}

The implementation of the code above will lead to panic, why? Go to language in reference type variable, we must not only declare it when in use, but also to allocate memory space for it, otherwise we have no way to store value. As for the value of the type of statement you do not need to allocate memory space, because they have a good default memory space allocated at the time of declaration. To allocate memory, it leads out of today's new and make. Go and make new languages ​​are two built-in functions, mainly used to allocate memory.

new

is a new built-in functions, its function signature as follows:

func new(Type) *Type

among them,

  • Type indicates the type, new function accepts a parameter, which is a type
  • * Type indicates the type of pointer, new function returns a pointer to the memory address type.

less common new function, using a new function obtained is the type of pointer, and the value of the zero value corresponding to the type of the pointer. for example:

func main() {
	a := new(int)
	b := new(bool)
	fmt.Printf("%T\n", a) // *int
	fmt.Printf("%T\n", b) // *bool
	fmt.Println(*a)       // 0
	fmt.Println(*b)       // false
}	

The sample code in the beginning of this section var a *intonly declares a pointer variable but did not initialize a pointer as the reference type and have a need to initialize memory space after, you can assign to it. You should use the new built-in functions can be normal after their assignment for a initialized as follows:

func main() {
	var a *int
	a = new(int)
	*a = 10
	fmt.Println(*a)
}

make

also make for memory allocation, different from new, only used slice, map and create chan's memory , and the type of return it is these three type itself, rather than their pointer type, because these three types is reference types, so there is no need to return to their hands up. function signature make the following functions:

func make(t Type, size ...IntegerType) Type

make function is irreplaceable, we use the slice, map and channel, they both need to make to initialize before you can operate on them. This we have explained in the previous chapter, we will explain in detail about the channel in subsequent chapters.

The examples in this section beginning in var b map[string]intjust declare a variable b is a variable of type map, and then need something like the following sample code as make use initialization function can be assigned key-value pairs:

func main() {
	var b map[string]int
	b = make(map[string]int, 10)
	b["沙河娜扎"] = 100
	fmt.Println(b)
}

New and make a difference

  1. Both are used for memory allocation.
  2. make only for initializing slice, map and channel, or the return of the three types of reference itself;
  3. And for the new type of memory allocation, memory type and a value corresponding to the zero value of the return pointer is a pointer type.

​​​​​​​

Reference herein Levin week's blog , and add some of their own understanding

 

Published 14 original articles · won praise 7 · views 1527

Guess you like

Origin blog.csdn.net/weixin_39966701/article/details/105337108