Appending/inserting/deleting slice elements
Slices use arrays as their underlying storage, but it is not possible to grow arrays when you run out of space. Because of this, if an append
operation exceeds the slice capacity, a new and larger array is allocated, and slice contents are copied to this new array.
How to do it...
To add new values to the end of the slice, use the append
built-in function:
// Create an empty integer slice islice := make([]int, 0) // Append values 1, 2, 3 to islice, assign it to newSlice newSlice := append(islice, 1, 2, 3) // islice: [] // newSlice: [1 2 3] // Create an empty integer slice islice = make([]int, 0) // Another integer slice with 3 elements otherSlice := []int{1, 2, 3} // Append 'otherSlice' to 'islice' newSlice = append(islice, otherSlice...) newSlice = append(newSlice, otherSlice...) // islice: [] // otherSlice: [1 2 3] // newSlice: [1 2 3 1 2 3]
To remove elements from the beginning or the end of a...