Home »
Golang
Go Slice vs Array
Last Updated : May 27, 2025
In Go, both arrays
and slices
are used to store collections of elements, but they have important differences in behavior and usage. In this chapter, we will learn the differences between them with the help of examples.
What is an Array?
An array is a fixed-size collection of items of the same type. The size of an array is part of its type, and it cannot be changed after declaration.
Example
This example shows how to declare and use an array:
package main
import "fmt"
func main() {
var numbers [3]int = [3]int{10, 20, 30}
fmt.Println("Array:", numbers)
}
When executed, this program outputs:
Array: [10 20 30]
What is a Slice?
A slice is a flexible, dynamically-sized view into an array. Unlike arrays, slices can grow and shrink.
Example
This example shows how to create and use a slice:
package main
import "fmt"
func main() {
fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println("Slice:", fruits)
}
When executed, this program outputs:
Slice: [Apple Banana Cherry]
Key Differences Between Slice and Array
This table shows the main difference between an array and a table:
Aspect |
Difference |
Size |
Arrays have a fixed size, while slices are dynamically sized. |
Declaration |
Arrays include the size in their type; slices do not. |
Usage |
Slices are used more often due to their flexibility. |
Memory |
Slices are references to underlying arrays, making them more efficient in many scenarios. |
Comparison Example
This example compares an array and a slice:
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3} // Array with fixed size
slc := []int{4, 5, 6} // Slice with dynamic size
fmt.Println("Array:", arr)
fmt.Println("Slice:", slc)
}
When executed, this program outputs:
Array: [1 2 3]
Slice: [4 5 6]
Modifying Elements
Both arrays and slices allow modifying elements by index, but slices can also be resized or appended.
Example
Here, we modify and append to a slice, but not an array:
package main
import "fmt"
func main() {
array := [2]string{"Go", "Lang"}
slice := []string{"Hello"}
array[1] = "Programming"
slice = append(slice, "World")
fmt.Println("Modified Array:", array)
fmt.Println("Appended Slice:", slice)
}
When executed, this program outputs:
Modified Array: [Go Programming]
Appended Slice: [Hello World]
Exercise
Select the correct option to test your understanding of the differences between slices and arrays in Go.
- An array in Go has a ___ size.
- A slice in Go can be resized using ___.
- Which of the following is a valid slice declaration?
Advertisement
Advertisement