doujieluo5875 2019-02-16 19:37
浏览 42
已采纳

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

Why both these destroy functions do not change pointer to nil and how can I create such function?

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)
    }

}

Outputs:

&{1 1}
&{2 2}

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

  • 写回答

1条回答 默认 最新

  • doudui6756 2019-02-16 19:41
    关注

    You need a pointer to pointer to change a pointer's value.

    Here's your code sample, modified to do this (playground):

    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)
        }
    }
    

    In your current code

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

    Inside destroy, p is a value the holds the address of a position struct. By assigning something to p itself, you're simply making it hold the address of some other position struct (or nil). You're not modifying the original pointer passed in.

    This isn't different from a function trying to modify its argument by assigning to it:

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

    The go spec says, in the section about calls and call parameters:

    After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value back to the calling function when the function returns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据