值传递
golang都是值传递,没有引用传递。 看起来像是引用传递的,其实也是对指针地址进行了copy。
func changIntValue(x *int) {
*x = 2 // Whatever variable caller passed in will now be 2
y := 7
x = &y // has no impact on the caller because we overwrote the pointer value!
}传入一个*int,结果值是2.
再看一个slice和type的例子:
package main
import "fmt"
type EType struct {
A int
}
func main() {
a := []int{1, 2, 3}
changeSlice(a)
b := a
a[2] = 4
fmt.Printf("%T, %v, %p, %p \n", a, a, a, &a)
fmt.Printf("%T, %v, %p, %p \n", b, b, b, &b)
t := EType{A: 1}
fmt.Println("type example: ", t)
changeStruct(t)
fmt.Println("type example after change: ", t)
}
func changeSlice(s []int) {
fmt.Printf("inner changeSlice: %T, %v, %p, %p \n", s, s, s, &s)
s[0] = 5
}
func changeStruct(t EType) {
t.A = 10
}
//inner changeSlice: []int, [1 2 3], 0xc000018018, 0xc000010048
//[]int, [5 2 4], 0xc000018018, 0xc000010030
//[]int, [5 2 4], 0xc000018018, 0xc0000100a8
//type example: {1}
//type example after change: {1}for range改动不生效的问题
for range这有个坑,生成的变量是值传递,会在loop完成后,进行销毁回收,展示下错误用法
var tmp yyyType
for _, item := range slice {
item.xxx = xxx
tmp = &item
}结果是item值没有改变,tmp指向空值
正确用法:
var tmp yyyType
for idx, item := range slice {
slice[idx].xxx = xxx
tmp = &slice[idx]
}