Sobes.tech
Senior

What operations exist on slices in Go?

sobes.tech AI

Answer from AI

In Go, slices are dynamic arrays that support the following operations:

  1. Creating a slice:

    s := []int{1, 2, 3}
    s2 := make([]int, 5) // slice of length 5
    
  2. Accessing elements:

    x := s[0] // first element
    s[1] = 10 // assignment
    
  3. Changing length with append:

    s = append(s, 4, 5)
    
  4. Slicing a slice:

    sub := s[1:3] // elements with indices 1 and 2
    
  5. Copying slices:

    dst := make([]int, len(s))
    copy(dst, s)
    
  6. Removing an element:

    // remove element at index i
    s = append(s[:i], s[i+1:]...)
    
  7. Iterating:

    for i, v := range s {
        fmt.Println(i, v)
    }
    
  8. Getting length and capacity:

    length := len(s)
    capacity := cap(s)
    

Thus, the main operations on slices include creation, access, resizing with append, slicing, copying, removing elements, and obtaining metadata (length, capacity).