In golang, a slice is a reference to a contiguous fragment of an array. This fragment can be the entire array or a subset of some items identified by the start and end indexes. The internal structure of slices in the Go language includes address, size and capacity. Slices are generally used to quickly operate a data set. If a data set is compared to cutting a cake, a slice is the "piece" you want. The cutting process includes starting from Where to start (the starting position of the slice) and how big to cut (the size of the slice), the capacity can be understood as the size of the pocket holding the slice.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
A slice is a reference to a continuous fragment of an array, so a slice is a reference type (so more similar to the array type in C/C, or the list type in Python). This fragment can It is the entire array, or it can be a subset of some items identified by the start and end indexes. It should be noted that the items identified by the end index are not included in the slice.
The internal structure of slices in the Go language includes address, size and capacity. Slices are generally used to quickly operate a data set. If a data set is compared to cutting a cake, a slice is the "piece" you want. , the cutting process includes where to start (the starting position of the slice) and how big to cut (the size of the slice). The capacity can be understood as the size of the pocket holding the slice, as shown in the figure below.
Figure: Slice structure and memory allocation
Generating a new slice from an array or slice
The slice points to a continuous memory area by default, which can be an array or the slice itself.
Generating slices from a continuous memory area is a common operation. The format is as follows:
slice [开始位置 : 结束位置]
The syntax is as follows:
slice: represents the target slice object;
Start position: corresponds to the index of the target slice object;
End position: corresponds to the end index of the target slice.
Generate a slice from an array, the code is as follows:
var a = [3]int{1, 2, 3} fmt.Println(a, a[1:2])
where a is an array with 3 integer elements, initialized to values 1 to 3, using a [1:2] can generate a new slice, and the code running result is as follows:
[1 2 3] [2]
where [2] is the result of a[1:2] slice operation.
Generating a new slice from an array or slice has the following characteristics:
The number of elements taken out is: end position - starting position;
The element taken out does not include the index corresponding to the end position. The last element of the slice is obtained using slice[len(slice)];
When the default starting position is used, it means starting from the continuous From the beginning of the area to the end position;
When the default end position is used, it means from the start position to the end of the entire continuous area;
Both at the same time By default, it is equivalent to the slice itself; when both
are 0, it is equivalent to an empty slice and is generally used for slice reset.
When taking the slice element value according to the index position, the value range is (0~len(slice)-1). If it exceeds the limit, a runtime error will be reported. When the slice is generated, the end The position can be filled in len(slice) but no error will be reported. [Related recommendations: Go video tutorial]
Let’s get familiar with the characteristics of slicing through examples.
1) Generate slices from the specified range
Slices and arrays are inseparable. If the array is understood as an office building, then slicing is to separate different consecutive floors. Rent to users. The rental process requires selecting the start floor and end floor. This process will generate slices. The sample code is as follows:
var highRiseBuilding [30]int for i := 0; i < 30; i++ { highRiseBuilding[i] = i + 1 } // 区间 fmt.Println(highRiseBuilding[10:15]) // 中间到尾部的所有元素 fmt.Println(highRiseBuilding[20:]) // 开头到中间指定位置的所有元素 fmt.Println(highRiseBuilding[:2])
The code output is as follows:
A 30-story high-rise building is constructed in the code. The element values of the array range from 1 to 30, representing different independent floors. The output results are different rental and sale plans.
The code description is as follows:
Line 8, try to rent out an interval floor.
Line 11, for rent above 20 floors.
Line 14, for rent below 2 floors, usually commercial shops.
Slices are a bit like pointers in C language. Pointers can perform operations, but the cost is that memory operations are out of bounds. Slices increase the size based on pointers and constrain the memory area corresponding to the slice. , the address and size inside the slice cannot be manually adjusted when using the slice, so the slice is safer and more powerful than the pointer.
2) Represents the original slice
In the format of generating slices, when the start and end positions are ignored, the generated slice will represent the same as the original slice slice, and the data content of the generated slice is consistent with the original slice. The code is as follows:
a := []int{1, 2, 3} fmt.Println(a[:])
a 是一个拥有 3 个元素的切片,将 a 切片使用 a[:] 进行操作后,得到的切片与 a 切片一致,代码输出如下:
3) 重置切片,清空拥有的元素
把切片的开始和结束位置都设为 0 时,生成的切片将变空,代码如下:
a := []int{1, 2, 3} fmt.Println(a[0:0])
代码输出如下:
直接声明新的切片
除了可以从原有的数组或者切片中生成切片外,也可以声明一个新的切片,每一种类型都可以拥有其切片类型,表示多个相同类型元素的连续集合,因此切片类型也可以被声明,切片类型声明格式如下:
var name []Type
其中 name 表示切片的变量名,Type 表示切片对应的元素类型。
下面代码展示了切片声明的使用过程:
// 声明字符串切片 var strList []string // 声明整型切片 var numList []int // 声明一个空切片 var numListEmpty = []int{} // 输出3个切片 fmt.Println(strList, numList, numListEmpty) // 输出3个切片大小 fmt.Println(len(strList), len(numList), len(numListEmpty)) // 切片判定空的结果 fmt.Println(strList == nil) fmt.Println(numList == nil) fmt.Println(numListEmpty == nil)
代码输出结果:
代码说明如下:
第 2 行,声明一个字符串切片,切片中拥有多个字符串。
第 5 行,声明一个整型切片,切片中拥有多个整型数值。
第 8 行,将 numListEmpty 声明为一个整型切片,本来会在{}中填充切片的初始化元素,这里没有填充,所以切片是空的,但是此时的 numListEmpty 已经被分配了内存,只是还没有元素。
第 11 行,切片均没有任何元素,3 个切片输出元素内容均为空。
第 14 行,没有对切片进行任何操作,strList 和 numList 没有指向任何数组或者其他切片。
第 17 行和第 18 行,声明但未使用的切片的默认值是 nil,strList 和 numList 也是 nil,所以和 nil 比较的结果是 true。
第 19 行,numListEmpty 已经被分配到了内存,但没有元素,因此和 nil 比较时是 false。
切片是动态结构,只能与 nil 判定相等,不能互相判定相等。声明新的切片后,可以使用 append() 函数向切片中添加元素。
使用 make() 函数构造切片
如果需要动态地创建一个切片,可以使用 make() 内建函数,格式如下:
make( []Type, size, cap )
其中 Type 是指切片的元素类型,size 指的是为这个类型分配多少个元素,cap 为预分配的元素数量,这个值设定后不影响 size,只是能提前分配空间,降低多次分配空间造成的性能问题。
示例如下:
a := make([]int, 2) b := make([]int, 2, 10) fmt.Println(a, b) fmt.Println(len(a), len(b))
代码输出如下:
其中 a 和 b 均是预分配 2 个元素的切片,只是 b 的内部存储空间已经分配了 10 个,但实际使用了 2 个元素。
容量不会影响当前的元素个数,因此 a 和 b 取 len 都是 2。
温馨提示
使用 make() 函数生成的切片一定发生了内存分配操作,但给定开始与结束位置(包括切片复位)的切片只是将新的切片结构指向已经分配好的内存区域,设定开始与结束位置,不会发生内存分配操作。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of What is slice in golang. For more information, please follow other related articles on the PHP Chinese website!