How to Delete Element from Slice in Go: Simple Guide
To delete an element from a slice in Go, use slicing and the
append function to combine parts before and after the element. For example, slice = append(slice[:index], slice[index+1:]...) removes the element at index.Syntax
The common syntax to delete an element at a specific index from a slice slice is:
slice[:index]: selects all elements before theindex.slice[index+1:]: selects all elements after theindex.append(slice[:index], slice[index+1:]...): joins these two parts, effectively removing the element atindex.
go
slice = append(slice[:index], slice[index+1:]...)
Example
This example shows how to delete the element at index 2 from a slice of integers.
go
package main import "fmt" func main() { numbers := []int{10, 20, 30, 40, 50} index := 2 // element 30 // Delete element at index 2 numbers = append(numbers[:index], numbers[index+1:]...) fmt.Println(numbers) // Output: [10 20 40 50] }
Output
[10 20 40 50]
Common Pitfalls
Common mistakes when deleting from slices include:
- Not using the
...operator after the second slice inappend, which causes a compile error. - Trying to delete an element with an
indexout of range, which causes a runtime panic. - Modifying the slice while iterating over it without adjusting the index, which can skip elements.
go
package main import "fmt" func main() { nums := []int{1, 2, 3, 4} index := 1 // Wrong: missing ... causes compile error // nums = append(nums[:index], nums[index+1:]) // Correct: nums = append(nums[:index], nums[index+1:]...) fmt.Println(nums) // Output: [1 3 4] }
Output
[1 3 4]
Quick Reference
Remember these tips when deleting from slices:
- Use
append(slice[:i], slice[i+1:]...)to remove element ati. - Check that
iis within slice bounds. - Use the
...operator to expand the second slice. - Deleting changes the slice length and order.
Key Takeaways
Use append with slicing and the ... operator to delete an element from a slice.
Always ensure the index is valid to avoid runtime errors.
Deleting an element shifts later elements left and reduces slice length.
Forget the ... operator after the second slice causes compile errors.
Avoid modifying a slice while iterating without adjusting indexes.