Slices in Go are dynamic data structures that provide flexibility and convenience when working with collections of data. While they are built on top of arrays, slices offer additional features that allow them to change in size dynamically.
To define a slice, you can omit the length, similar to an array:
var mySlice []string // a slice of strings
You can initialize a slice with values:
var mySlice = []string{"First", "Second", "Third"}
// or
mySlice := []string{"First", "Second", "Third"}
To create an empty slice of a specific length, you can use the make()
function:
mySlice := make([]string, 3) // a slice of 3 empty strings
Appending one or more items to an existing slice creates a new slice:
mySlice := []string{"First", "Second", "Third"}
newSlice := append(mySlice, "Fourth", "Fifth")
It’s important to assign the result of append()
to a new slice to avoid compiler errors. The original slice remains unchanged, and a new one is created.
To duplicate a slice and make it independent of the original, you can use the copy()
function:
mySlice := []string{"First", "Second", "Third"}
newSlice := make([]string, 3)
copy(newSlice, mySlice)
If the slice you’re copying to doesn’t have enough space, only the available items will be copied.
You can also initialize a slice from an array:
myArray := [3]string{"First", "Second", "Third"}
mySlice = myArray[:]
Multiple slices can share the same underlying array:
myArray := [3]string{"First", "Second", "Third"}
mySlice := myArray[:]
mySlice2 := myArray[:]
mySlice[0] = "test"
fmt.Println(mySlice2[0]) // "test"
Modifying one slice will affect the shared underlying array and other slices created from it.
Like arrays, each item in a slice is stored in consecutive memory locations. If you anticipate performing operations on the slice, you can request a larger capacity to ensure space is readily available:
newSlice := make([]string, 0, 10) // an empty slice with a capacity of 10
You can also extract portions of a slice using slicing syntax:
mySlice := []string{"First", "Second", "Third"}
newSlice := mySlice[:2] // get the first 2 items
newSlice2 := mySlice[2:] // ignore the first 2 items
newSlice3 := mySlice[1:3] // new slice with items at positions 1-2
Slices in Go offer a powerful and convenient way to work with collections of data. Understanding their features and capabilities can greatly enhance your programming experience.