因为append doesn't take a list to append, but rather one or more items to append。您可以在 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.
请注意,append 并不总是重新分配底层数组(这会导致性能和内存使用方面的问题)。就此示例而言,您很好,但是如果您尝试将相同的内存用于多种用途,它可能会咬您一口。一个(做作,也许不清楚)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)
}
当您尝试在将 foo 添加到其子切片后打印它时,您会得到新旧内容的奇怪混合。
如果共享底层数组存在问题,您可以使用字符串(字符串字节是不可变的,非常有效地防止意外覆盖)或像我在上面使用 append([]byte(nil), foo[:10]...) 所做的那样制作副本。