Clive B.
—You don’t know how to delete an element from a slice in Go.
If you know the index of the element(s) that you want to delete from a slice, you can use the Delete
function from the slices
package.
Note: The slices.Delete
function is O(len(s)-i)
, where i
represents the start of the range to be deleted. If you need to delete many items, it is better to delete them all in a single call than to delete one item at a time. This function also expects the input to be valid.
package main import ( "fmt" "slices" ) func main() { letters := []string{"a", "b", "c", "d", "e"} letters = slices.Delete(letters, 1, 4) fmt.Println(letters) }
This prints:
[a e]
Attempting to delete an invalid range will cause a panic, as in the example below:
package main import ( "fmt" "slices" ) func main() { letters := []string{"a", "b", "c", "d", "e"} letters = slices.Delete(letters, 1, 10) }
Because 10
is an invalid index, this returns the following panic:
panic: runtime error: slice bounds out of range [:10:5]
If you want to search for specific elements in a slice, you can use the slices.DeleteFunc
instead.
For example, you could search for all the even numbers in a slice as follows:
package main import ( "fmt" "slices" ) func main() { example := []int{0, 1, 2, 3, 4, 5, 6} example = slices.DeleteFunc(example, func(n int) bool { return n%2 != 0 // Remove odd numbers. }) fmt.Println(example) }
This prints an output of the slice with the odd numbers removed:
[0 2 4 6]
Note: This example passes the func(n int)
filter function to slices.DeleteFunc
. Because this is a generic filter function, its argument must match the type of the slice. In this case, it accepts an int
because example
is a slice of integers. If you instead wanted to filter a specific string from strings, you would change the argument of the filter function to string
:
package main import ( "fmt" "slices" ) func main() { example := []string{"a", "b", "c"} example = slices.DeleteFunc(example, func(s string) bool { return s == "b" }) fmt.Println(example) }
This would print:
[a c]
slices
packageTasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.