What is the Difference Between Array and Slice?
Overview
In the Go language, the slice is more widely used instead of an array. It is because a slice is more convenient, powerful, and flexible as compared to an array. It is also because it is a lightweight data structure in the Go language. It is similar to an array in terms of storing the values except for the fact that the size of the slice can be changed.
An array is a collection of elements of the same data type. It has a fixed size and is used for storing homogenous elements in the memory. The elements in an array are indexed by using the bracket [] for instance, if a second element is to be retrieved from the array then arrayname[1] is used because indexing starts from 0.
Note:
- Array size should be non-negative integers.
- All elements would be given their zero values.
- Arrays cannot be resized.
Arrays in Go
Syntax: To declare an array, we write:
where n denotes the number of elements in an array, and T represents the type of each element.
Create an array:
To initialize an array, we have the following options:
For creating an array, look at the example given below:
Output:
Output:
Explanation:
In this example, the var keyword is used for initializing the variable which is named as num in this example. The num[10] denotes that an array is to be created with size 10 and int denotes the data type of the value that is to be stored inside an array.
Accessing an array:
Output:
Explanation:
In this, the elements are accessed using a for loop. In each iteration, the element of an array is printed by using the index “i” in an array.
Multidimensional Array
Multi-dimensional array, as the name suggests, is an array of arrays containing elements of the same type. In Go, the multi-dimensional array can be created using the syntax:
The multi-dimensional array can either be created using the var keyword or by using a shorthand declaration.
Note:
If the cell in the multidimensional array is not initialized by the user, then it will automatically get initialized by zero by the compiler and is done automatically.
To understand it better, let’s take an example:
package main
Output:
Explanation:
In this example, an array “a” is declared and initialized with 5 rows and 2 columns. The elements are accessed using the for loop and are printed.
Array Methods
Array indexing:
If an array has 5 elements then indexing ranges from 0 to 4. If the index range is invalid and the compiler can detect this we get the error: index out of bounds. Otherwise, the code compiles just fine, and at runtime, we get an error: runtime error: index out of range.
Example:
Array iteration:
- len()
It is used to return the number of elements in the array.
For example: len(array_name)
To iterate over an array we can use:
- for loop with len(a_id)
- for loop with range a_id:
- range returns index
- range returns index and value at that index
Example:
Output:
Array modification:
- If an array is assigned to a new variable a copy of the original array is assigned to the new variable.
- If we don’t want a different copy then we can pass the address of the array to the new variable.
- If an array is passed to a function a copy of the original array is assigned to the new variable in that function.
- If we want to work with the same array in the function too, we need to pass the address of the array.
Example:
Output:
Drawbacks of Arrays
The following are the disadvantages of an array:
- Fixed Size:
Arrays in Go have a fixed size, which is determined at the time of declaration. Once an array is created, its size cannot be changed. This lack of dynamic resizing can be limiting when you need to handle a variable number of elements or when the size of the data is not known in advance. - Memory Inefficiency: Arrays in Go occupy a fixed amount of memory, regardless of the number of elements stored in the array. If an array is declared with a large size but only a few elements are populated, the remaining memory will be wasted. This inefficiency can become significant when dealing with large arrays or when the array size needs to be adjusted dynamically.
- Limited Functionality:
Arrays in Go have limited built-in functionality compared to slices. Slices provide more flexible operations such as appending, resizing, and slicing. Arrays lack these convenient operations and require manual handling for such tasks. For example, if you want to add elements to an array, you need to create a new array with a larger size and copy the existing elements. - Pass-by-Value:
When an array is passed as an argument to a function in Go, a complete copy of the array is made. This pass-by-value behavior can be inefficient for large arrays as it involves copying the entire contents of the array. In contrast, slices are passed by reference, which is more efficient because only a small header is copied. - Lack of Dynamic Length Information:
Arrays in Go do not provide a built-in way to determine their length. You need to keep track of the array length manually and pass it around when needed. This can lead to potential errors if the length is not managed correctly.
Slices Introduction
Slice is similar to the array with the difference that the size of a slice can be changed dynamically. To declare a slice we can use one of the following ways:
- var s_id[] T:
- s_id is the slice name.
- T is the slice type.
- Note: size is not mentioned
The Internal Implementation of Slices
The slice acts as a descriptor of the segment in an array. It consists of a pointer, which points to an array, the segment’s length, and its capacity.

When a make variable is used, an array is created using the specified parameter. The structure of it looks something like this:

The slice does not copy the data instead it creates a new slice value that again points to the original array. This makes manipulation operation in slice efficient.

Slice is a reference type referring to an underlying array. Modifying elements will modify the array elements and other slices that refer to that array will also see those modifications.
Declaration of Slices
We can create a slice using the slice literal just like the array literal except we don’t specify the size.
We can use shorthand declaration also:
We can also use the make function for slice:
- It is a library function for creating slices.
- the cap is optional. If a cap is not provided it defaults to len.
Example:
Output:
General Slice Operations Such as Appending at the End, Printing Length, and Iterating through Elements
- len()
It returns the number of elements in the slice. - cap()
it returns the number of elements the slice can accommodate - append()
This function can be used to append new elements at the end of the given slice.
We can also append one slice to another using the … operator.
Disadvantages of the Slice
The following are the disadvantages of a slice in the Go language:
- Memory Overhead:
Slices in Go have a small memory overhead compared to simple arrays. Each slice includes a pointer to the underlying array, its length, and its capacity. This additional information consumes extra memory, especially when dealing with many small slices. - Mutable and Shared State:
Slices are mutable data structures, meaning their contents can be modified. This can introduce complexity, particularly in concurrent programs where multiple goroutines may access and modify the same slice simultaneously. Proper synchronization mechanisms, such as locks or channels, must be used to ensure safe concurrent access. - Inefficient Appending:
While Go provides the append() function for adding elements to a slice, it can be inefficient in certain scenarios. When the capacity of the underlying array is insufficient to accommodate the new element, append() creates a new array with a larger capacity, copies the existing elements, and adds the new element. This operation has a time complexity of , where n is the size of the slice. Frequent or repetitive appending can result in poor performance. - Lack of Type Safety:
Slices in Go are not strictly type-safe. A slice can hold elements of different types, and this flexibility can lead to runtime errors if the expected type assumptions are violated. Ensuring type safety may require additional runtime checks or type assertions.
Conclusion
- In the Go language, the slice is more widely used instead of an array. It is because a slice is more convenient, powerful, and flexible as compared to an array.
- An array is a collection of elements of the same data type. It has a fixed size and is used for storing homogenous elements in the memory.
- To declare an array, we write:
- Slice is similar to the array with the difference that the size of a slice can be changed dynamically.
- To declare a slice we can use one of the following ways: