Junior — Middle
How to extract the first n elements from an array?
sobes.tech AI
Answer from AI
In Go, to extract the first n elements from a slice, you can use slicing operation:
arr := []int{1, 2, 3, 4, 5}
n := 3
// Check that n does not exceed the length of the slice
if n > len(arr) {
n = len(arr)
}
firstN := arr[:n]
fmt.Println(firstN) // Output: [1 2 3]
It is important to check that n does not exceed the length of the slice to avoid runtime panic.