func append(slice []Type, elems ...Type) []Type
|
参数名称
|
含义
|
|
slice
|
待添加元素的切片
|
|
elems
|
要添加的元素
|
append函数允许一次性添加多个值。
给切片添加元素
package main
import "fmt"
func main() {
demo := make([]int, 0, 1)
demo = append(demo, 1)
fmt.Println("demo:", demo)
// outputs: demo: [1]
给切片添加多个元素
package main
import "fmt"
func main() {
demo := make([]int, 0, 1)
demo = append(demo, 1, 3, 5)
fmt.Println("demo:", demo)
// outputs: demo: [1 3 5]
合并其它切片
借助append函数,可以将一个切片合并到另一个切片中:
package main
import "fmt"
func main() {
s1 := []int{23, 26, 28}
s2 := []int{3, 6, 9}
s1 = append(s1, s2...)
fmt.Println(s1)
// output: [23 26 28 3 6 9]
append返回的新切片与原切片是否指向同一块内存地址
根据切片的性质,当使用append函数给切片添加元素后,切片的length未超过append前的cap,则切片不会扩容,因此append返回的切片与原切片指向同一个内存地址。反之,append返回扩容后的切片,与原切片的内存地址不同:
package main
import "fmt"
func main() {
source := make([]int, 0, 3)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000b6020
source = append(source, 1)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000b6020
source = append(source, 2, 3)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000ba000
package mainimport "fmt"func main() {
s1 := []int{0, 1, 2, 3}
s2 := []int{4, 5, 6, 7} s1 = append(s1, s2...)
fmt.Println(s1)
// [0 1 2 3 4 5 6 7]
切片是对其底层数组的某一段的引用。
切片有 len 和 cap 两个属性,代表切片的引用长度和切片的容量(从切片的引用起点位置到其底层数组最末端的长度。因为其底层数组的长度是固定的,这也就是意味着容量是指切片可引用的最大宽度)。
append 函数
slice2 := append(slice1, 23, 15)
以上对切片 slice1 进行 append 操作。该操作遵循以下原则:
append 函数对一个切片 slice1 进行追加操作,并返回另一个长度为
func combineSortedSlice(n1, n2 []int) {
if len(n1) == 0 {
combineResult = append(combineResult, n2...)
return
if len(n2) == 0 {
combineResult = append(combineResult, n1...)
return
if n1[0] < n.
a = append(a, 1) // 追加1个元素
a = append(a, 1, 2, 3) // 追加多个元素, 手写解包方式
a = append(a, []int{1,2,3}...) // 追加一个切片, 切片需要解包
不过需要注意的是,在使用 append() 函数为切片动态添加元...