douchan7552
2015-12-14 20:41 阅读 135
已采纳

在Go中比较指针

I am reading in my Go book that pointers are comparable. It says: two pointers are equal if and only if they Point to the same variable or both are nil.

So why is my following code printing 'true' when comparing two pointers which are pointing to two different variables?

func main() {
    var p = f()
    var q = f2()
    fmt.Println(*p == *q) // why true?
}

func f() *int {
    v := 1
    return &v
}

func f2() *int {
    w := 1
    return &w
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    duanchi4544 duanchi4544 2015-12-14 20:44

    You aren't comparing the pointers themselves because you use the 'derefernce operator' * which returns the value stored at that address. In your example code, you've called the methods which returned two different pointers. The value stored at each of those different addresses happens to be 1. When you derefernce the pointer you get the value stored there so you're just comparing 1 == 1 which is true.

    Comparing the pointers themselves you get false;

    package main
    
    import "fmt"
    
    func main() {
        var p = f()
        var q = f2()
        fmt.Println(*p == *q) // why true?
    
        fmt.Println(p == q) // pointer comparison, compares the memory address value stored
        // rather than the the value which resides at that address value
    
        // check out what you're actually getting
        fmt.Println(p) // hex address values here
        fmt.Println(q)
        fmt.Println(*p) // 1
        fmt.Println(*q) // 1
    }
    
    func f() *int {
        v := 1
        return &v
    }
    
    func f2() *int {
        w := 1
        return &w
    }
    

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

    点赞 评论 复制链接分享
  • dougangxin5695 dougangxin5695 2015-12-15 01:16
    package main
    
    import "fmt"
    
    func main() {
        var p = f()
        var q = f2()
    
        fmt.Println(*p == *q)
        /* is true, since *p = *q = 1 */
    
        fmt.Println(p == q)
        /* is false, since *p and *q store two different memory addresses */
    }
    
    func f() *int {
        v := 1
        return &v
    }
    
    func f2() *int {
        w := 1
        return &w
    }
    

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

    点赞 评论 复制链接分享

相关推荐