1:切片作为函数传参
package main
import "fmt"
func test(target *[]int) {
*target = append(*target, 1)
fmt.Println(*target)
}
func test2(target []int) {
target = append(target, 1)
fmt.Println(target)
}
func main () {
var tt = []int{4,5}
test(&tt)
fmt.Println(tt)
fmt.Println("--------------")
var tt2 = []int{4,5}
test2(tt2)
fmt.Println(tt2)
}
输出:
[4 5 1]
[4 5 1]
--------------
[4 5 1]
[4 5]
原因分析,加了一些打印如下:
package main
import "fmt"
func test(target *[]int) {
fmt.Printf("process before:address of slice %p \n", *target)
*target = append(*target, 1)
fmt.Println(*target)
fmt.Printf("process after:address of slice %p \n", *target)
}
func test2(target []int) {
fmt.Printf("process before:address of slice %p \n", target)
target = append(target, 1)
fmt.Println(target)
fmt.Printf("process after:address of slice %p \n", target)
}
func main () {
var tt = []int{4,5}
fmt.Printf("init:address of slice %p \n", tt)
test(&tt)
fmt.Println(tt)
fmt.Printf("after:address of slice %p \n", tt)
fmt.Println("--------------")
var tt2 = []int{4,5}
fmt.Printf("init:address of slice %p \n", tt)
test2(tt2)
fmt.Println(tt2)
fmt.Printf("after:address of slice %p \n", tt2)
}
输出如下:
init:address of slice 0xc000016060
process before:address of slice 0xc000016060
[4 5 1]
process after:address of slice 0xc000014060
[4 5 1]
after:address of slice 0xc000014060
--------------
init:address of slice 0xc000014060
process before:address of slice 0xc0000160a0
[4 5 1]
process after:address of slice 0xc000014080
[4 5]
after:address of slice 0xc0000160a0
真相大白:
根据打印可以看出,切片直接传参,传的参数的切片结构体的副本,俩副本指向同样的底层数组。进过函数内部 append 操作后,切片重新生成,修改后的值无法传到函数外,修改无效。如果传的是切片地址,则操作对象一直是同一个结构体和底层数组。