Sobes.tech
Junior — Middle

How to extract the first N elements from an array or list?

sobes.tech AI

Answer from AI

In Go, slicing is used to extract the first N elements from a slice. If you have a slice arr, the first N elements can be obtained as:

firstN := arr[:N]

It's important to ensure that N does not exceed the length of the slice, otherwise a panic will occur. For example:

arr := []int{1, 2, 3, 4, 5}
N := 3
if N > len(arr) {
    N = len(arr)
}
firstN := arr[:N]
fmt.Println(firstN) // Output: [1 2 3]
How to extract the first N elements from an array or… - sobes.tech