Sobes.tech
Senior

What is a slice and how does it differ from an array?

sobes.tech AI

Answer from AI

In Go, an array is a fixed-size structure that contains elements of the same type. The size of the array is set at declaration and cannot be changed during program execution.

A slice is a dynamic, resizable view of an array. It is a structure that contains a pointer to an array, a length, and a capacity. Slices allow working with subsets of an array and can automatically expand when needed.

Main differences:

  • Size: an array has a fixed size, a slice is dynamic.
  • Passing: arrays are passed by value (copied), slices are passed by reference (pointer to the array).
  • Flexibility: slices can be expanded using the append function, arrays cannot.

Example:

var arr [3]int = [3]int{1, 2, 3} // fixed-size array

var s []int = arr[0:2] // slice referencing part of the array

s = append(s, 4) // slice expands, a new array is created if necessary
What is a slice and how does it differ from an array… - sobes.tech