Home > Article > Backend Development > Does golang slicing require make?
Slice is a special data structure in Golang. This data structure is easier to use and manage data collections. Slices are built around the concept of dynamic arrays, which can automatically grow and shrink on demand.
Create a slice through the make() function
Use Golang's built-in make() function to create a slice. At this time, you need to pass in a parameter to specify the length of the slice:
// 创建一个整型切片 // 其长度和容量都是 5 个元素 slice := make([]int, 5)
At this time, only the length of the slice is specified, then the capacity and length of the slice are equal. You can also specify the length and capacity separately:
// 创建一个整型切片 // 其长度为 3 个元素,容量为 5 个元素 slice := make([]int, 3, 5)
When you specify the length and capacity respectively, the length of the created slice and the underlying array is the specified capacity, but not all array elements can be accessed after initialization.
Note that Golang does not allow the creation of slices with a capacity smaller than the length. When the capacity of the created slice is smaller than the length, an error will be reported at compile time:
// 创建一个整型切片 // 使其长度大于容量 myNum := make([]int, 5, 3)
Creating slices through literals
Another commonly used method of creating slices is to use slice literals. This method is similar to creating an array, except that there is no need to specify the value in the [] operator. The initial length and capacity will be determined based on the number of elements provided during initialization:
// 创建字符串切片 // 其长度和容量都是 3 个元素 myStr := []string{"Jack", "Mark", "Nick"} // 创建一个整型切片 // 其长度和容量都是 4 个元素 myNum := []int{10, 20, 30, 40}
When using slice literals to create slices, you can also set the initial length and capacity. All that is done is to give the required length and capacity as an index at initialization time. The following syntax shows how to use indexing to create a slice with a length and capacity of 100 elements:
// 创建字符串切片 // 使用空字符串初始化第 100 个元素 myStr := []string{99: ""}
For more golang knowledge, please pay attention to the golang tutorial column.
The above is the detailed content of Does golang slicing require make?. For more information, please follow other related articles on the PHP Chinese website!