Appending to and copying slices
The built-in functions
append
andcopy
assist in common slice operations. For both functions, the result is independent of whether the memory referenced by the arguments overlaps.
Today and tomorrow we’ll look at the first of those two, append
:
The variadic function
append
appends zero or more valuesx
to a slices
and returns the resulting slice of the same type ass
. The core type ofs
must be a slice of type[]E
. The valuesx
are passed to a parameter of type...E
and the respective parameter passing rules apply. As a special case, if the core type ofs
is[]byte
, append also accepts a second argument with core typebytestring
followed by...
. This form appends the bytes of the byte slice or string.append(s S, x ...E) S // core type of S is []E
Alright. So that’s a lot of text to say what “mostly” boils down to:
append
takes an arbitrary slice as its first argument, then zero or more additional arguments, of the appropriate type, and returns a new slice that contians the argument(s) appended to the original slice.
One special case is mentioned: If the first argument is a byte slice (i.e. []byte
), the following argument may be a string, followed by ...
. Without the exception, only []byte
would be permitted.
bs := []byte{'H', 'e', 'l', 'l', 'o', ',', ' '}
bs = append(bs, "world"...)
fmt.Println(string(bs)) // Prints: Hello, world
(See it in the playground.)
Without this exception, the above code would have to be written as follows (which, of course, still works):
bs := []byte{'H', 'e', 'l', 'l', 'o', ',', ' '}
bs = append(bs, []byte("world")...)
fmt.Println(string(bs))
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)