Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #291 Remove sublist

Delete all the elements from index i (included) to index j (excluded) from the list items.

items = append(items[:i], items[j:]...)

Use this when the elements don't have a pointer type.
copy(items[i:], items[j:])
for k, n := len(items)-j+i, len(items); k < n; k++ {
	items[k] = nil
}
items = items[:len(items)-j+i]

Use this when the elements of items have a pointer type.

The for loop sets unused memory to nil, to avoid a memory leak.
import "slices"
items = slices.Delete(items, i, j)

This generic func slices.Delete works for all slice types.
items.removeRange(i, j);

New implementation...
< >
programming-idioms.org