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.

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

报告相同问题?