Sobes.tech
Junior — Middle

Kas saaksite selgitada, milleks kasutatakse funktsiooni len lõikude puhul Go keeles ja kuidas see töötab?

sobes.tech AI

Vastus AI-lt

In Go, the len function for slices returns the number of elements in that slice. A slice is a structure that contains a pointer to an array, a length, and a capacity.

When you take a slice, for example s := arr[2:5], the length of the slice is the number of elements between indices 2 and 5 (excluding 5), which is 3.

Example:

arr := []int{10, 20, 30, 40, 50}
s := arr[1:4] // elements with indices 1, 2, 3
fmt.Println(len(s)) // will print 3

Thus, len allows you to find out how many elements a slice contains, which is important for iterations and checks.