Go Reference ยท Built-in Functions
Go append() function
Reference for Go append(): add elements or another slice to a slice, how capacity growth works, why you must use the result, and aliasing pitfalls.
append adds elements to the end of a slice and returns the resulting slice. If the slice has enough capacity, the elements are written into the existing backing array; otherwise a larger array is allocated, the old elements are copied, and the new slice points at it.
Because the result may refer to a different array, you must always use the return value, usually by assigning it back to the same variable. Calling append(s, x) and ignoring the result is a compile error.
s = append(s, 1) s = append(s, 2, 3, 4) s = append(s, other...)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func append(s S, x ...E) S func append(s []byte, x string...) []byte // special case
S is a slice type with element type E.
| Parameter | Description |
|---|---|
s |
The slice to extend. May be nil. |
x |
Zero or more values assignable to E, or a slice followed by .... |
Returns: a slice of the same type holding the old elements followed by the new ones. When s is nil and nothing is appended, the result is nil.
Usage notes
- Always keep the result. The returned slice may share the original array or not; never assume which.
- Growth. When capacity is insufficient, the runtime allocates a bigger array. For small slices capacity roughly doubles; for large ones growth is smaller (about 1.25x plus a constant), and the exact numbers are an implementation detail and are rounded to allocator size classes. Do not rely on them.
- Amortized cost. Appending is O(1) amortized per element. If you know the final size, preallocate with
make([]T, 0, n)to avoid repeated copying. - Aliasing. When capacity allows,
appendwrites into the shared array and can overwrite data visible through other slices (see the second example). Uses[:i:i]orslices.Cloneto force a copy. - Append to itself.
s = append(s, s...)is valid and doubles the content. - Elements removed from the end still occupy the array and stay reachable; set pointer elements to
nilbefore shrinking to let the garbage collector free them. - Nil slices. Appending to a nil slice works; there is no need to initialize it.
- Strings. You can append a string to a
[]bytewithappend(b, str...). - Helpers. The
slicespackage providesInsert,Delete,ConcatandGrowfor common patterns.