我们先看一下append的源码
// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
//
// As a special case, it is legal to append a string to a byte slice, like this:
//
// slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type
源码中定义了三种apped的使用场景:
1、为切片添加同种类型的元素
slice = append(slice, elem1, elem2)
2、将两个切片拼接到一起
slice = append(slice, anotherSlice...)
3、当切片是byte类型时,允许添加string类型的元素
slice = append([]byte("hello "), "world"...)
package main
import "fmt"
func main() {
a := make([]int, 5, 10)
for i := 0; i < len(a); i++ {
a[i] = i
}
fmt.Println(a)
a = append(a, 5,6, 7, 8, 9, 10)
fmt.Println(a)
}
输出结果
[0 1 2 3 4]
[0 1 2 3 4 6 7 8 9 10]
package main
import "fmt"
func main() {
a := make([]int, 5, 10)
for i := 0; i < len(a); i++ {
a[i] = i
}
fmt.Println(a)
b := make([]int, 5, 10)
for i := 5; i < len(b)+5; i++ {
b[i-5] = i
}
fmt.Println(b)
a = append(a, b...)
fmt.Println(a)
}
输出结果
[0 1 2 3 4]
[5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
根据append可以添加切片的性质,使用append可以实现删除一个切片中某一个元素或删除某一段连续元素的功能。
package main
import "fmt"
func main() {
a := make([]int, 5, 10)
for i := 0; i < len(a); i++ {
a[i] = i
}
fmt.Println(a)
a = append(a[:2], a[4:]...) //删除a[2],a[3]
fmt.Println(a)
}
输出结果
[0 1 2 3 4]
[0 1 4]
package main
import "fmt"
func main() {
a := []byte("Hello")
fmt.Println(a, string(a))
a = append(a, "World"...)
fmt.Println(a, string(a))
}
输出结果
[72 101 108 108 111] Hello
[72 101 108 108 111 87 111 114 108 100] HelloWorld