Overview
Remove an item from a shopping cart slice in Go without overwriting the caller's slice: slices share their array, so build a new one instead.
- a slice is a window on an array
- s[:i] shares the array
- copy into a new slice
Short Course
A slice is a window on an array, and s[:i] shares that array. Trap:
append(s[:i], s[i+1:]...) writes over the caller's items. Build a new slice
instead.
a := []int{1, 2, 3}
b := append(a[:0], a[1:]...)
b // [2 3]
a // [2 3 3]: overwritten
Task
Write Without(items []string, i int) []string: a new slice without the item
at index i, leaving items unchanged. Example:
Without([]string{"pen", "ink", "cap"}, 1) → [pen cap].
Test Suites
Pending
Next
Output