**append的时候,如果slice容量足够,不需要扩容,则slice底层数组的值会变动。如果需要扩容,会形成新的数组指针给到slice,原来的数组值是不会变的。对于想要在函数调用过程中改变上层传入的slice里的值的写法要注意!!!**
#### **容量足够**
```
func main() {
line := "123456789abcdefghijklmnopqrstuvw" // len 32
l := []byte(line) // 默认cap 32
aaa(l[27:30])
logger.Infof("out : %v %v", len(l), cap(l))
logger.Infof("l %v", string(l))
}
func aaa(line []byte) {
logger.Infof("in 1: %v %v", len(line), cap(line))
logger.Infof("in line: %v", string(line))
line = append(line, []byte("AAA")...)
logger.Infof("in 2: %v %v", len(line), cap(line))
logger.Infof("in line2: %v", string(line))
}
```
输出
```
2022-08-31 15:38:58 file=TestThings/main.go:111 level=info in 1: 3 5
2022-08-31 15:38:58 file=TestThings/main.go:112 level=info in line: stu
2022-08-31 15:38:58 file=TestThings/main.go:114 level=info in 2: 5 5
2022-08-31 15:38:58 file=TestThings/main.go:115 level=info in line2: stuAA
2022-08-31 15:38:58 file=TestThings/main.go:100 level=info out : 32 32
2022-08-31 15:38:58 file=TestThings/main.go:101 level=info l 123456789abcdefghijklmnopqrstuAA
```
#### **容量不够**
```
func main() {
line := "123456789abcdefghijklmnopqrstuvw" // len 32
l := []byte(line) // 默认cap 32
aaa(l[27:30])
logger.Infof("out : %v %v", len(l), cap(l))
logger.Infof("l %v", string(l))
}
func aaa(line []byte) {
logger.Infof("in 1: %v %v", len(line), cap(line))
logger.Infof("in line: %v", string(line))
line = append(line, []byte("AAA")...)
logger.Infof("in 2: %v %v", len(line), cap(line))
logger.Infof("in line2: %v", string(line))
}
```
输出
```
2022-08-31 16:00:35 file=TestThings/main.go:105 level=info in 1: 3 5
2022-08-31 16:00:35 file=TestThings/main.go:106 level=info in line: stu
2022-08-31 16:00:35 file=TestThings/main.go:108 level=info in 2: 6 16
2022-08-31 16:00:35 file=TestThings/main.go:109 level=info in line2: stuAAA
2022-08-31 16:00:35 file=TestThings/main.go:100 level=info out : 32 32
2022-08-31 16:00:35 file=TestThings/main.go:101 level=info l 123456789abcdefghijklmnopqrstuvw
```
有疑问加站长微信联系(非本文作者)