Slices vs arrays in Go¶
In Go, both arrays and slices are used to store collections of data, but they differ significantly in flexibility and behavior.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]
Arrays¶
An array is a fixed-size collection of variables of the same type.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] When defining an array, you must specify its capacity (e.g., [2]string), which determines the exact number of elements it can hold.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]
Because arrays have a static length, you cannot add more items than the initial capacity allows.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]
// Arrays allow us to make a collection of variables of the same type
func getData() (customers [2]string) {
customer := "Marcel Dempers"
customers[0] = customer
customers[1] = "Bob Smith"
return customers
}
Slices¶
Slices are a dynamically-sized, flexible view into arrays.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] Unlike arrays, slices do not require a fixed size to be declared at initialization, allowing the collection to grow or shrink as needed.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]
To add elements to a slice beyond its initial capacity, the built-in append function is used.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]
// Slices are a dynamically-sized view into arrays
func getData() (customers []string) {
customers = []string{ "Marcel Dempers", "Bob Smith" }
// Add more items dynamically
customers = append(customers, "Ben Spain")
return customers
}
Key Differences¶
| Feature | Arrays | Slices |
|---|---|---|
| Size | Fixed size (e.g., [5]int).^[400-devops__09-Scripting-Language__golang__introduction__readme.md] |
Dynamic size (e.g., []int).^[400-devops__09-Scripting-Language__golang__introduction__readme.md] |
| Capacity | Static capacity determined at declaration.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] | Can grow dynamically using append.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] |
| Usage | Best when the number of elements is known and unchanging. | Generally preferred for most use cases requiring lists.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] |
Sources¶
^[400-devops__09-Scripting-Language__golang__introduction__readme.md]