切片函数传递,在函数中使用append,在调用用输出未见改动,具体见代码和运行图:
```go
package main
import "fmt"
type student struct {
id int
name string
age int
}
func demo(ce []student) {
ce[1].age = 999
ce = append(ce, student{4, "xiaowan2g", 98})
fmt.Printf("%p\n", ce)
fmt.Println(len(ce), cap(ce))
fmt.Println(ce)
}
func main() {
var ce []student
ce = []student{
student{1, "xiaoming", 22},
student{2, "xiaozhang", 33},
}
ce = append(ce, student{3, "xiaowang", 56})
fmt.Printf("%p\n", ce)
fmt.Println(len(ce), cap(ce))
demo(ce)
fmt.Println(len(ce), cap(ce))
fmt.Println(ce)
}
```
运行截图:
![【golang】切片函数传递,在函数中使用append,在调用用输出未见改动,具体见图](https://cdn.learnku.com/uploads/images/202107/06/67616/ZUBFmNU6jd.png!large)
ce 的地址是一样的,预计结果应该都是输出 [{1 xiaoming 22} {2 xiaozhang 999} {3 xiaowang 56} {4 xiaowan2g 98}],未能如愿,不知道问题出在哪里?求教!
有疑问加站长微信联系(非本文作者)