Go Slices #
Slices are a flexible, powerful, and more commonly used alternative to arrays in Go. Unlike arrays, slices:
- Do not have a fixed length; their length can change dynamically.
- Reference an underlying array, meaning multiple slices can share the same data.
- Provide convenient functions to append, copy, and manipulate data.
This section covers:
Introduction to Slices #
Slices are declared using the following syntax:
slice_name := []datatype{values}
- The
[]datatype
part indicates that it is a slice of a specific type. - Values can be provided at declaration, or the slice can be created empty and appended later.
Slices provide more flexibility than arrays while still being type-safe.
Example: Creating a simple slice
package main
import ("fmt")
func main() {
fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println(fruits)
}
Result:
[Apple Banana Cherry]
Key Characteristics of Slices #
Dynamic Size Slices can grow and shrink using built-in functions like
append()
andcopy()
.Reference Semantics Slices point to an underlying array. Modifying one slice may affect other slices that reference the same array.
Length and Capacity
len(slice)
returns the number of elements in the slice.cap(slice)
returns the capacity of the underlying array.
Example: Length and Capacity
package main
import ("fmt")
func main() {
numbers := []int{1,2,3,4,5}
fmt.Println("Length:", len(numbers))
fmt.Println("Capacity:", cap(numbers))
}
Result:
Length: 5
Capacity: 5
Slices are the foundation for dynamic data structures in Go and are heavily used in real-world programs.