introduction
In Go, slices are a very powerful and flexible data structure that is based on arrays but also provides the ability to dynamically resize. Slicing is very common in Go language and is almost the preferred way to process sequence data. This article will introduce in detail the use of slice declaration, initialization, operation, expansion and other uses in Go language based on actual cases.
1. Definition and internal structure of slices
1.1 Basic definition of slices
Slicing is an abstract representation of arrays in Go language, which provides a dynamic way to process sequence data. A slice is not an array, but it contains references to the array inside. A slice has three key properties:
- Pointer to the underlying array: Point to an array of data that is actually stored in the slice.
- Length of slice (len): The number of elements currently contained in the slice.
- Capacity of slices (cap): The number of elements from the beginning of the slice to the end of its underlying array.
1.2 Slice statement
There are several ways to declare slices, and the following are some common declared methods:
use
var
Keyword declares slices, but does not initialize:
var mySlice []int
at this time,
mySlice
is a nil slice, i.e. it does not point to any underlying array, with both length and capacity of 0.use
:=
Automatically deduce type declaration slices:
mySlice := []int{}
at this time,
mySlice
is an empty integer slice with a length of 0, but the underlying array has been allocated (capacity of 0 or system default).use
make
Function creates slices:
mySlice := make([]int, 5)
pass
make
The function can create a slice of a specified length and can optionally specify the capacity. If the capacity is not specified, the capacity is equal to the length.
2. Initialization and creation of slices
2.1 Usemake
Functions create slices
make
Functions are built-in functions in Go language, specifically used to create composite types such as slices, maps, and channels. usemake
When a function creates a slice, you can specify the length and capacity of the slice:
slice := make([]int, 5, 10) // Create an integer slice with a length of 5 and a capacity of 10
2.2 Create slices using slice literals
Slices can also be initialized with literals like arrays, but do not need to specify the length of the array:
myStr := []string{"Jack", "Mark", "Nick"} // Create and initialize a string slicemyNum := []int{10, 20, 30, 40} // Create and initialize an integer slice
2.3 Creating slices based on arrays
Slices can be created based on an existing array. Slices can only use some or all elements of the array, or even create a larger slice than the array (as long as it does not exceed the capacity of the array).
months := [...]string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} q2 := months[3:6] // Create slices based on arrays to represent the second quarter
3. Slicing operation
3.1 Accessing slice elements
Accessing slice elements is similar to accessing array elements, using index operators[]
。
mySlice := []int{1, 2, 3, 4, 5} (mySlice[0]) // Output: 1
3.2 Dynamic changes in slice length
Slices support dynamically increasing or decreasing elements, which is the biggest difference between slices and arrays. Slice expansion is usually built-inappend
Function implementation.
mySlice := []int{1, 2, 3} mySlice = append(mySlice, 4, 5) // Append two elements to the end of the slice(mySlice) // Output: [1 2 3 4 5]
3.3 Slice expansion mechanism
When usingappend
When a function appends an element to a slice, if the capacity of the slice is not enough to accommodate the newly added elements, the Go language will automatically expand the capacity. When expanding, the capacity of the new slice is usually twice the original volume (when the original slice length is less than 1024). If the capacity after expansion is still insufficient, continue to expand according to this rule until all elements can be accommodated.
oldSlice := []int{1, 2, 3, 4, 5} newSlice := append(oldSlice, 6, 7, 8, 9) ("newSlice len:", len(newSlice), "cap:", cap(newSlice)) // The output may be: newSlice len: 9 cap: 10
3.4 Slice slices
A slice can also be created based on another slice, which is called a slice of slices. By specifying the start index and the end index (optionally specifying capacity), a new slice can be created from a slice.
firstHalf := months[:6] // The first half of the yearq1 := firstHalf[:3] //Quarter 1
3.5 Copying of slices
Go language providescopy
Function, used to copy one slice into another. If the size of the two slices is different, copy according to the size of the smaller slice.
src := []int{1, 2, 3} dst := make([]int, 2) copy(dst, src) // Copy the first two elements of src to dst(dst) // Output: [1 2]
4. Traversal of slices
The traversal method of slices is the same as that of arrays, and it supports index traversal andfor range
Traversal.
4.1 Index traversal
slice := []int{1, 2, 3, 4, 5} for i := 0; i < len(slice); i++ { (slice[i]) }
4.2 for range
Traversal
slice := []int{1, 2, 3, 4, 5} for index, value := range slice { (index, value) }
5. Application cases of slices
5.1 Calculate the sum of integers in slices
func sum(numbers []int) int { total := 0 for _, number := range numbers { total += number } return total } func main() { numbers := []int{1, 2, 3, 4, 5} ("Sum:", sum(numbers)) // Output: Sum: 15}
5.2 Find the maximum value in the slice
func findMax(numbers []int) int { max := numbers[0] for _, number := range numbers { if number > max { max = number } } return max } func main() { numbers := []int{3, 5, 2, 8, 1} ("Max:", findMax(numbers)) // Output: Max: 8}
5.3 Slice as function parameter
When a slice is used as a function parameter, a reference to the slice is passed, so modifications to the slice inside the function will affect the original slice.
func modifySlice(s []int) { s[0] = 100 } func main() { mySlice := []int{1, 2, 3} modifySlice(mySlice) (mySlice) // Output: [100 2 3]}
6. Summary
Slicing is a very powerful and flexible data structure in Go language that provides the ability to dynamically resize by encapsulating arrays. The operations of slices include declaration, initialization, accessing elements, dynamic changes, traversal, copying, etc. When a slice is used as a function parameter, a reference to the slice is passed, so modifications to the slice will affect the original slice. Through the study of this tutorial, I hope readers can deeply understand and master the usage of slices in Go.
The above is the detailed content of the in-depth analysis and application practice of Go language slices. For more information about Go language slices, please pay attention to my other related articles!