我从 Go 开始,我很难理解函数内部结构的指针和引用。
考虑示例https://play.golang.org/p/zd8La4ecNXw
package main
import "fmt"
type User struct {
Name string
}
func main() {
// 1st
u := User{Name: "Anne"}
fmt.Println("1st: ", &u.Name)
fmt.Println("1st: ", u.Name)
Modify1(u)
fmt.Println("1st: ", u.Name)
// 2nd
fmt.Println()
v := &User{Name: "Anne"}
fmt.Println("2nd: ", &v.Name)
fmt.Println("2nd: ", v.Name)
Modify2(v)
fmt.Println("2nd: ", v.Name)
// 3rd
fmt.Println()
y := &User{Name: "Anne"}
fmt.Println("3rd: ", &y.Name)
fmt.Println("3rd: ", y.Name)
Modify3(&y)
fmt.Println("3rd: ", y.Name)
// 4th
fmt.Println()
z := &User{Name: "Anne"}
fmt.Println("4th: ", &z.Name)
fmt.Println("4th: ", z.Name)
Modify4(z)
fmt.Println("4th: ", z.Name)
}
func Modify1(u User) {
fmt.Println("func: ", &u.Name)
u.Name = "Duncan"
fmt.Println("func: ", u.Name)
}
func Modify2(v *User) {
fmt.Println("func: ", &v.Name)
v = &User{Name: "Paul"}
fmt.Println("func: ", v.Name)
}
func Modify3(y **User) {
fmt.Println("func: ", &y)
fmt.Println("func: ", &(*y).Name)
*y = &User{Name: "Bob"}
fmt.Println("func: ", (*y).Name)
}
func Modify4(z *User) {
fmt.Println("func: ", &z.Name)
z.Name = "John"
fmt.Println("func: ", z.Name)
}
除了第一个示例,我没有问题,所有其他示例似乎都指向原始结构分配,但第二个不更改调用者值。
为什么会发生这种情况,为什么这与3rd和4th不同?
哆啦的时光机
相关分类