Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go
items = append(items, x)
copy(items[1:], items)
items[0] = x

This implementation is verbose, but it will often not allocate, when items has enough capacity.
items = append([]T{x}, items...)

items has type []T.
This implementation always allocates a full new slice.
func prepend[S ~[]T, T any](items *S, x ...T) {
	*items = append(x, *items...)
}

This generic func always allocates a full new slice.
The variadic argument x accepts one or more values to be inserted at the beginning.
func prepend[S ~[]T, T any](items *S, x ...T) {
	*items = append(*items, x...)
	copy((*items)[len(x):], *items)
	copy(*items, x)
}

This generic func does not always allocate (depending on the capacity of items).
The variadic argument x accepts one or more values to insert at the beginning.
(def items2 (conj items x))

conj take a list and an item, in that order, and appends the item to the list at the front.

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