This page looks best with JavaScript enabled

Array and slice in Go

 ·  ☕ 2 min read  ·  ✍️ t1

In Go (Golang), arrays and slices are both used to store collections of data, but they have different properties and behaviors that suit different use cases. Here’s a breakdown of the key differences between arrays and slices in Go:

Arrays

  1. Fixed Size: Arrays have a fixed size that is defined when they are declared. The size cannot be changed once the array is initialized.
  2. Memory Layout: Arrays are value types, meaning that when an array is assigned to a new variable or passed to a function, a complete copy of the array is made.
  3. Declaration Syntax: Arrays are declared with both the element type and the number of elements (which must be a constant expression). For example: var a [5]int.

Slices

  1. Dynamic Size: Slices are dynamically-sized, flexible view into the elements of an array. They do not have a fixed size, and can grow or shrink as needed.
  2. Underlying Array: Slices are reference types, which means they reference an underlying array. Changing the elements of a slice modifies the corresponding elements of its underlying array.
  3. Memory Efficiency: When a slice is passed to a function, only the slice descriptor is passed (which includes a pointer to the element, the length of the slice, and its capacity), not the entire data.
  4. Declaration and Initialization: Slices can be created using the built-in make function, by slicing an existing array, or using a slice literal. For example, s := []int{1, 2, 3} creates a slice containing three integers.
  5. Built-in Functions: Slices are supported by built-in functions such as append, which can be used to add elements dynamically to a slice.

Practical Differences

  • Use Cases: Arrays are used when the number of elements is known and constant. Slices are preferred when you need a sequence with a dynamic size or when you need to take advantage of Go’s built-in functions for handling collections.
  • Performance: Operations on arrays can be slightly faster since they do not require additional indirection to access the underlying elements. However, slices offer more flexibility and are more commonly used in Go programming due to their dynamic nature.

In summary, slices in Go provide a more flexible and powerful way to work with data collections compared to arrays, which are simpler but limited to fixed-size scenarios. Slices are generally preferred in Go unless a fixed-size collection is specifically required.

Share on

t1
WRITTEN BY
t1
Dev