Sobes.tech
Junior — Middle

What methods exist for processing and using slices passed to a function in your code?

sobes.tech AI

Answer from AI

In Go, slices are passed to functions by value, but the value of a slice contains a pointer to the underlying array, along with its length and capacity. This means that changes to the elements of the slice inside the function will be visible outside, but changing the slice itself (for example, assigning a new slice) will not.

Main ways to work with passed slices:

  • Modify the elements of the slice directly, e.g., s[0] = 10.
  • Add elements using append. If this causes reallocation of the underlying array, external changes will not be reflected unless you return the new slice.
  • To change the length of the slice inside a function and reflect the changes outside, you can return a new slice or pass a pointer to the slice.

Example:

func modifySlice(s []int) []int {
    s[0] = 100          // changes the first element
    s = append(s, 200)  // may create a new array
    return s            // return the new slice
}

func main() {
    s := []int{1, 2, 3}
    s = modifySlice(s)
    fmt.Println(s) // [100 2 3 200]
}
What methods exist for processing and using slices… - sobes.tech