Introduction
Slices let you work with lists of items easily. Common slice operations help you add, remove, or change items in these lists.
Slices let you work with lists of items easily. Common slice operations help you add, remove, or change items in these lists.
var s []Type // Add item s = append(s, item) // Remove item at index i s = append(s[:i], s[i+1:]...) // Get slice from index start to end-1 sub := s[start:end] // Length of slice length := len(s)
append adds items to the end of a slice.
Removing an item uses append to join parts before and after the item.
numbers := []int{1, 2, 3} numbers = append(numbers, 4)
letters := []string{"a", "b", "c", "d"}
letters = append(letters[:2], letters[3:]...)items := []string{"apple", "banana", "cherry", "date"}
sub := items[1:3]count := len(items)
This program shows how to add, remove, slice, and count items in a slice of fruits.
package main import "fmt" func main() { fruits := []string{"apple", "banana", "cherry"} fmt.Println("Original slice:", fruits) // Add a fruit fruits = append(fruits, "date") fmt.Println("After append:", fruits) // Remove the second fruit (index 1) fruits = append(fruits[:1], fruits[2:]...) fmt.Println("After removal:", fruits) // Get a slice of first two fruits firstTwo := fruits[:2] fmt.Println("First two fruits:", firstTwo) // Length of slice fmt.Println("Number of fruits:", len(fruits)) }
Remember slices are like windows to arrays; changing a slice can affect the underlying array.
Use append carefully to avoid unexpected results when removing items.
Slices hold lists of items you can change easily.
Use append to add or remove items.
You can get parts of slices using slicing syntax [start:end].
mySlice[2:5] do in Go?mySlice[2:5] extracts elements starting at index 2 up to, but not including, index 5. Go slices use half-open intervals, so the element at index 5 is not included in the new slice.5 to a slice nums in Go?append returns a new slice with the element added, so you must assign it back. nums = append(nums, 5) correctly assigns the result back to nums. append(nums, 5) ignores the returned slice. nums.append(5) uses invalid method syntax. nums += 5 is invalid for slices.nums := []int{1, 2, 3, 4, 5}
slice := nums[1:4]
slice[0] = 10
fmt.Println(nums)slice := nums[1:4] references the original array elements at indexes 1, 2, and 3. Changing slice[0] to 10 changes nums[1] because slices share the underlying array. Output: [1 10 3 4 5]nums := []int{1, 2, 3}
newSlice := nums[1:4]
fmt.Println(newSlice)nums has length 3, so valid indices are 0 to 2. Attempting nums[1:4] tries to access index 3 which is out of range, causing a runtime panic.data := []int{2, 4, 6, 8, 10, 12}, how can you create a new slice containing only the even numbers greater than 6 using slicing and append?data[3:] gets these elements. To create a new slice (not referencing original), append to empty slice: newSlice := append([]int{}, data[3:]...).Pass the test and this pattern moves unknown