–
下面是go指针传递到函数中的坑,指针传递到函数中,是复制了一份相同的变量到函数中,函数里面赋值了,并不代表外面的指针也被赋值了 package main import "fmt" type Person struct { a int b string } func changeA(tmp, tmpB *Person) { tmp = tmpB } func changeA1(tmp, tmpB *Person) { *tmp = *tmpB } func main() { var tmpA Person ptmpB := &Person{12, "abc"} changeA(&tmpA, ptmpB) //changeA1(&tmpA, ptmpB) fmt.Println(tmpA.a, tmpA.b) fmt.Println(ptmpB.a, ptmpB.b) } package main import "fmt" type Person struct { a int b string } func changeA(ptmp, ptmpB *Person) { ptmp.a = ptmpB.a ptmp.b = ptmpB.b } func main() { var tmpA Person ptmpB := &Person{12, "abc"} changeA(&tmpA, ptmpB) fmt.Println(tmpA.a, tmpA.b) fmt.Println(ptmpB.a, ptmpB.b) }
–
–
–
评论前必须登录!
注册