Sobes.tech
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) and cap(slice). For a nil slice, both length and capacity are 0.
  • Use the append operator to add elements. append will automatically create a new slice with allocated memory if the original slice is nil.

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]