Junior — Middle
Kuidas välja võtta massiivist esimesed n elementi?
sobes.tech AI
Vastus AI-lt
In Go, to extract the first n elements from a slice, you can use the 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 panics.