Junior — Middle
Millised toimingud on lubatud Go-s, kui töötab lõiguga, kui see ei olnud selgelt algatatud?
sobes.tech AI
Vastus AI-lt
In Go, if a slice is not explicitly initialized (i.e., it has the value nil), the following actions can be performed:
- Check if it is
nil(for example,if slice == nil), which is useful for determining whether the slice has been initialized. - Obtain its length and capacity using
len(slice)andcap(slice). For anilslice, both length and capacity are 0. - Use the
appendoperator to add elements.appendwill automatically create a new slice with allocated memory if the original slice isnil.
However, you cannot access slice elements by index if it is nil or empty, as this will cause a panic.
Example:
var s []int // s == nil
fmt.Println(s == nil) // true
fmt.Println(len(s)) // 0
s = append(s, 1) // now s is initialized and contains [1]