代码如下:
type Student struct {
Name string
}
func remove(stu *Student) {
fmt.Println("2----", stu)
stu = nil
fmt.Println("3----", stu)
}
func main() {
stu := &Student{"中国"}
fmt.Println("1----", stu)
remove(stu)
fmt.Println("4----", stu)
}
执行结果:
1---- &{中国}
2---- &{中国}
3---- <nil>
4---- &{中国}
代码中传递的是地址,为什么没有改变掉stu的值,在第4步的值仍然不变
有疑问加站长微信联系(非本文作者)

指针是对指向内容的引用,不是对指针变量的引用
import "fmt"
type Student struct { Name string }
func remove(stu Student) { fmt.Println("2----", stu) stu = Student{"我爱你"} fmt.Println("3----", stu) }
func main() { stu := &Student{"中国"} fmt.Println("1----", stu) remove(stu) fmt.Println("4----", stu) }
你要修改的是局部指针指向的变量的值,所以用*stu改变其值,否则stu只是改变了方法作用域内局部指针指向的变量,并没有改变外部指针指向的变量的值域
第一次回复,忘了用代码块了 ·*stu = Student{"我爱你"}·
package main
import ( "fmt" )
type Student struct { Name string }
func remove(stu *Student) { fmt.Println("2----", stu) stu = nil fmt.Println("3----", stu) }
func main() { stu := &Student{"中国"} fmt.Println("1----", stu) remove(&stu) fmt.Println("4----", stu) }
package main
import ( "fmt" )
type Student struct { Name string }
func remove(stu *Student) { fmt.Println("2----", stu) stu = nil fmt.Println("3----", stu) }
func main() { stu := &Student{"中国"} fmt.Println("1----", stu) remove(&stu) fmt.Println("4----", stu) }
预览和现实不同,格式管不了了……
赞一个
调用 remove 时实际上是把 stu 的指针复制了一份传入函数内部,在 remove 内部的 stu 可以理解为指向同一个块内存的不同指针,你打印一下指针的地址就知道了。
谢谢大家耐心解答,终于理解清楚了
打印下地址一看便知
可以看看这个:https://cloud.tencent.com/developer/doc/1101,里面有很详细的解释,要是遇到其他问题应该也能找到答案,希望能帮到你们咯