从方法或函数中将指针设置为 nil

Mar*_*iwa 2 go

为什么这两个destroy函数不将指针更改为 nil 以及如何创建这样的函数?

package main

import (
    "fmt"
)

type position struct {
    x int
    y int
}

func (p *position) destroy() {
    p = nil
}

func destroy(p *position) {
    p = nil
}

func main() {
    p1 := &position{1,1}
    p2 := &position{2,2}
    p1.destroy()
    destroy(p2)

    if p1 == nil {
        fmt.Println("p1 == nil")
    } else {
        fmt.Println(p1)
    }

    if p2 == nil {
        fmt.Println("p2 == nil")
    } else {
        fmt.Println(p2)
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

&{1 1}
&{2 2}
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/BmZjX1Hw24u

Eli*_*sky 6

您需要一个指向指针的指针来更改指针的值。

这是您的代码示例,经过修改以执行此操作(游乐场):

package main

import (
    "fmt"
)

type position struct {
    x int
    y int
}

func destroy(p **position) {
    *p = nil
}

func main() {
    p1 := &position{1, 1}
    destroy(&p1)

    if p1 == nil {
        fmt.Println("p1 == nil")
    } else {
        fmt.Println(p1)
    }
}
Run Code Online (Sandbox Code Playgroud)

在您当前的代码中

func destroy(p *position) {
    p = nil
}
Run Code Online (Sandbox Code Playgroud)

里面destroyp是一个保存结构体地址的值position。通过将某些内容分配给自身,您只需让它保存其他一些结构体(或)p的地址。您没有修改传入的原始指针。positionnil

这与尝试通过赋值来修改其参数的函数没有什么不同:

// This will not actually modify the argument passed in by the caller
func setto2(value int) {
  value = 2
}
Run Code Online (Sandbox Code Playgroud)

go 规范在有关调用和调用参数的部分中说:

在评估它们之后,调用的参数将按值传递给函数,并且被调用的函数开始执行。当函数返回时,函数的返回参数按值传递回调用函数。