What is the method of using slices in Go?
In Go, a slice is a dynamic array made up of a pointer to the array, its length, and capacity. Slices offer a convenient and flexible way to manipulate arrays.
Here is how to use the slice:
- Declare and initialize a slice.
- // Declare a slice
s := []int{1, 2, 3} // Initialize slice using literals
s := make([]int, 5) // Create a slice with specified length and capacity using make function - Accessing and modifying elements in a slice:
- s := []int{1, 2, 3}
fmt.Println(s[0]) // Accessing the first element of the slice
s[1] = 4 // Modifying the second element of the slice - Obtain the length and capacity of a slice:
- s := []int{1, 2, 3}
fmt.Println(len(s)) // Obtain the length of the slice
fmt.Println(cap(s)) // Obtain the capacity of the slice - “Slice: cutting into pieces”
- s := []int{1, 2, 3, 4, 5}
fmt.Println(s[1:3]) // Slice, get the second to third element [2 3]
fmt.Println(s[:3]) // Slice, get from the beginning to the third element [1 2 3]
fmt.Println(s[2:]) // Slice, get from the third element to the end [3 4 5] - Add elements to a slice.
- s is initialized as an integer slice containing the elements 1, 2, and 3. An element 4 is added to the end of the slice using the append function. Additionally, elements 5 and 6 are added to the end of the slice using the append function.
- Remove elements from a slice.
- s := []int{1, 2, 3}
s = append(s[:1], s[2:]…) // Remove the second element from the slice - Copy and paste:
- Create a new slice s2 with the same length as s1, then copy the elements from s1 to s2.
These are just the basic usage of slices, there are more advanced operations and methods available. You can refer to the official Go documentation to learn more about using slices.