Junior — Middle
Mis on operatsiooni ajakulud, kui otsitakse elementi indeksiga loendis?
sobes.tech AI
Vastus AI-lt
In Go, accessing an element of a slice by index has a time complexity of O(1), meaning it is performed in constant time. This is because a slice in Go is a structure with a pointer to an array, a length, and a capacity, and access to an element by index is done directly through the memory address.
Example:
package main
import "fmt"
func main() {
s := []int{10, 20, 30, 40}
fmt.Println(s[2]) // Will print 30
}
Therefore, searching for an element by index in a list (slice) in Go is very efficient.