What is the difference between an array and a slice in Go?

What is the difference between an array and a slice in Go? post thumbnail image

In Go, arrays and slices are both used to store collections of elements. The main differences between arrays and slices are:

  1. Size: Arrays have a fixed size that is determined at the time of declaration, while slices have a dynamic size that can change at runtime.
  2. Type: The size and type of an array are fixed at the time of declaration, while the size of a slice is dynamic and its type is determined by the type of the elements it contains.
  3. Initialization: Arrays can be initialized with values at the time of declaration, while slices are typically initialized using the make() function.
  4. Memory: Arrays are stored in contiguous memory locations, while slices are just references to arrays.
  5. Accessing Elements: Elements of an array are accessed using the square bracket notation, while elements of a slice are accessed using the same notation but with an additional colon to specify the range.
  6. Passing to Functions: Arrays are passed to functions by value, while slices are passed by reference, meaning that changes made to a slice inside a function will be reflected outside the function as well.

In general, slices are more commonly used in Go than arrays because of their dynamic nature and ability to easily manipulate collections of data.

Sample: Array

// Declaring an array with 3 elements of type int

var myArray [3]int

// Initializing an array with values

myArray = [3]int{1, 2, 3}

// Declaring and initializing an array with shorthand syntax

myArray := [...]int{1, 2, 3}

// Accessing and modifying elements in an array

myArray[0] = 4
fmt.Println(myArray[0]) // Output: 4

Sample: Slice

// Declaring a slice with a length of 3 and a capacity of 5

mySlice := make([]int, 3, 5)

// Initializing a slice with values

mySlice = []int{1, 2, 3}

// Appending values to a slice

mySlice = append(mySlice, 4)

// Accessing and modifying elements in a slice

mySlice[0] = 5
fmt.Println(mySlice[0]) // Output: 5

// Slicing a slice to create a new slice

newSlice := mySlice[1:3]
fmt.Println(newSlice) // Output: [2 3]

// Iterating over a slice using a for loop

for index, value := range mySlice {  
  fmt.Println(index, value)

// Getting the length and capacity of a slice

fmt.Println(len(mySlice)) // Output: 4
fmt.Println(cap(mySlice)) // Output: 5

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 23 = 24

Related Post