函数的参数传递机制可以分为两种,值传递和引用传递。
go里所有参数传递都是值传递,既把参数复制一份放到函数里去用。即使是指针,也是将指针复制一份再进行传递。
对于go函数里面传参为指针,传参方式是值传递。在这里有个例子。
package main
import "fmt"
type struct1 struct{
attr1 string
}
func main(){
var a *struct1
fmt.Println("addr of a:",&a)
someFunc(a)
}
func someFunc(b *struct1){
fmt.Println("addr of b:",&b)
}
输出等于:
addr of a: 0xc0000a2010
addr of b: 0xc0000a2020
这里可以看到,我们新建了一个指针 a,在someFunc()将a作为参数传递,生成了指针的复制b。
package main
import "fmt"
type struct1 struct{
attr1 string
}
func main(){
var a *struct1
fmt.Println("addr of a:",&a)
fmt.Println("value of a:",a)
someFunc(a)
}
func someFunc(b *struct1){
fmt.Println("addr of b:",&b)
fmt.Println("value of b:",b)
c := struct1{
attr1 : "111",
}
b = &c
fmt.Println("addr of b:",&b)
fmt.Println("value of b:",b)
fmt.Println("addr of c:",&c)
fmt.Println("value of c:",c)
}
输出等于:
addr of a: 0xc000088018
value of a: <nil>
addr of b: 0xc000088028
value of b: <nil>
addr of b: 0xc000088028
value of b: &{111}
addr of c: &{111}
value of c: {111}