Skip to content

Go slices versus arrays

In Go, the choice between using an array or a slice determines the memory layout and mutability of a collection.^[400-devops-09-scripting-language-golang-introduction-readme.md]

Arrays

Arrays in Go are used to create a fixed-size collection of variables of the same type^[400-devops-09-scripting-language-golang-introduction-readme.md]. They are strictly defined by their capacity; for example, an array defined as [2]string can hold exactly two elements^[400-devops-09-scripting-language-golang-introduction-readme.md].

Because of this fixed nature, individual elements are accessed and assigned via a zero-based index, such as customers[0]^[400-devops-09-scripting-language-golang-introduction-readme.md].

Slices

Slices provide a dynamically-sized view into arrays^[400-devops-09-scripting-language-golang-introduction-readme.md]. Unlike arrays, slices do not have a fixed capacity at declaration, allowing them to grow or shrink as needed^[400-devops-09-scripting-language-golang-introduction-readme.md].

To modify a slice after its creation, Go provides the built-in append function^[400-devops-09-scripting-language-golang-introduction-readme.md]. This function accepts a slice and a new value, adding the element to the collection dynamically^[400-devops-09-scripting-language-golang-introduction-readme.md].

Comparison

  • Sizing: Arrays require a predefined size (e.g., [2]string), whereas slices are flexible wrappers around arrays^[400-devops-09-scripting-language-golang-introduction-readme.md].
  • Mutability: To add data to an array, one must assign values to specific indices. To add data to a slice, one typically uses the append function to handle resizing automatically^[400-devops-09-scripting-language-golang-introduction-readme.md].
  • [[Go structs]]
  • [[Go control flow]]
  • [[Go loops]]

Sources

^[400-devops-09-scripting-language-golang-introduction-readme.md]