How to create a sub-slice from an existing slice in Golang?

To create a sub-slice from an existing slice in Golang, you can use the slice indexing notation slice[start:end].

Here's an example of creating a sub-slice from an existing slice in Golang:

package main import "fmt" func main() { // Creating the existing slice numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Creating a sub-slice using the existing slice subSlice := numbers[2:6] fmt.Println(subSlice) // Output: [3 4 5 6] }

In this example, an existing slice numbers is created. We then create a sub-slice subSlice by using the indexing notation numbers[2:6]. This creates a new sub-slice that includes elements from the index 2 up to, but not including, the index 6 of the numbers slice.

Note that modifying the sub-slice will also modify the original slice as they share the same underlying array. If you want to create a completely separate copy of the sub-slice, you can use the copy function:

package main import "fmt" func main() { // Creating the existing slice numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Creating a sub-slice using the existing slice subSlice := make([]int, 4) copy(subSlice, numbers[2:6]) fmt.Println(subSlice) // Output: [3 4 5 6] // Modifying the sub-slice does not affect the original slice subSlice[0] = 999 fmt.Println(subSlice) // Output: [999 4 5 6] fmt.Println(numbers) // Output: [1 2 3 4 5 6 7 8 9 10] }

In this modified example, we use the copy function to create a separate copy of the sub-slice. Modifying the copied sub-slice does not affect the original numbers slice.