go language commonly used functions: make

Brief introduction

Built-in functions used to make slice, map or allocate memory and initialize chan type of an object (note: this can only be used in three types)

Code

Use make to create a slice, map, chanel follows:

slice

// 长度为5,容量为10的slice,slice中的元素是int
var slice_ []int = make([]int,5,10)
fmt.Println(slice_)

var slice_1 []int = make([]int,5)
fmt.Println(slice_1)

var slice_2 []int = []int{1,2}
fmt.Println(slice_2)

Print Results:

[0 0 0 0 0]
[0 0 0 0 0]
[1,2]

Capacity of the slice is arranged (i.e., the length of the underlying array) with the third parameter. If sufficient capacity can be pre-, then the growth process of the data slice does not require replacement of the underlying array (with the copying process), so that a higher efficiency.

map

var m_ map[string]int = make(map[string]int)
m_["one"] = 1
fmt.Println(m_)

var m map[string]int = map[string]int{"1":1}
m["2"] = 2
fmt.Println(m)

Print Results:

map[one:1]
map[1:1 2:2]

According to the memory size to the size of the initial assignment, but the length of the distribution map is 0, if the size is ignored, then allocates a small-sized memory when allocating memory initialization

channel

Pipe buffer is initialized based buffer capacity. If the capacity is zero or negligible capacity, there is no pipeline buffer

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/103909097