Copying and Appending Slices

This lesson describes the method of copying a slice or appending a slice to provide flexibility.

Modifying slices

To increase the capacity of a slice one must create a new and larger slice and copy the contents of the original slice into it.

Use of the copy function

Its syntax is as:

func copy(dst, src []T) int

The function copy copies slice elements of type T from a source src to a destination dst, overwriting the corresponding elements in dst, and it returns the number of elements copied. Source and destination may overlap. The number of arguments copied is the minimum of len(src) and len(dst). When src is a string, the element type is byte.

Use of the append function

Its syntax is:

func append(s[]T, x ...T) []T

The function append appends zero or more values to a slice s and returns the resulting slice with the same type as s. The values, of course, have to be of the same type as the element-type T of s. If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large slice that fits both the existing slice elements and the additional values. Thus, the returned slice may refer to a different underlying array. The append always succeeds unless the computer runs out of memory.

If you want to append a slice y to a slice x, use the following form to expand the second argument to a list of arguments:

x = append(x, y...)

The following code illustrates the functions copy for copying slices, and append for appending new values to a slice.

Get hands-on with 1400+ tech skills courses.