Appending to and copying slices
The built-in functions
appendandcopyassist 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
appendappends zero or more valuesxto a slicesand returns the resulting slice of the same type ass. The core type ofsmust be a slice of type[]E. The valuesxare passed to a parameter of type...Eand the respective parameter passing rules apply. As a special case, if the core type ofsis[]byte, append also accepts a second argument with core typebytestringfollowed 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)