It's because append
doesn't take a list to append, but rather one or more items to append. You can adapt to this with a ...
on the second argument to append
:
package main
import "fmt"
var lettersLower = []rune("abcdefghijklmnopqrstuvwxyz")
var lettersUpper = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
func main() {
x := append(lettersLower, lettersUpper...)
fmt.Println(len(x))
}
Try it out on the Playground.
Note that append
does not always re-allocate the underlying array (that would cause problems in terms of performance and memory usage). You're fine as far as this sample goes, but it may bite you if you ever try to use the same memory for multiple purposes. A (contrived, perhaps unclear) example:
package main
import (
"fmt"
"os"
)
func main() {
foo := []byte("this is a BIG OLD TEST!!\n")
tst := []byte("little test")
bar := append(foo[:10], tst...)
// now bar is right, but foo is a mix of old and new text!
fmt.Print("without copy, foo after: ")
os.Stdout.Write(foo)
// ok, now the same exercise but with an explicit copy of foo
foo = []byte("this is a BIG OLD TEST!!\n")
bar = append([]byte(nil), foo[:10]...) // copies foo[:10]
bar = append(bar, tst...)
// this time we modified a copy, and foo is its original self
fmt.Print("with a copy, foo after: ")
os.Stdout.Write(foo)
}
When you try to print foo
after appending to a subslice of it, you get a weird mix of old and new content.
Where the shared underlying array is a problem, you could either use strings (string bytes are immutable, a pretty effective guard against accidental overwrites) or make a copy as I did with append([]byte(nil), foo[:10]...)
above.
[]rune
appenders that may come across this page. :) – Superintendency