What is the difference between Go arrays and slices?

In Go, an array is a fixed-size collection of elements of the same type. The size of the array is specified at the time of declaration and cannot be changed. The syntax for declaring an array is as follows:

var arr [5]int // declares an integer array of size 5

On the other hand, a slice is a dynamically-sized, flexible view into an underlying array. A slice is essentially a pointer to an array, along with a length and a capacity. Slices can be resized, unlike arrays. The syntax for declaring a slice is as follows:

var s []int // declares an integer slice

Slices are commonly created by taking a slice of an existing array using the **make()** function or the slice literal syntax. For example, to create a slice of length 3 and capacity 5 from an array of length 10:

arr := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
s := arr[2:5] // slice of length 3, starting from index 2 and ending at index 4

The main difference between arrays and slices is that arrays have a fixed size while slices can be resized dynamically. Additionally, arrays are passed by value in Go, while slices are passed by reference, meaning that changes made to a slice are reflected in the underlying array.

Related Questions You Might Be Interested