比较Go中的指针

fuf*_*x79 2 pointers go

我在Go书中读到指针是可比较的.它说:当且仅当它们指向同一个变量或两者都是零时,两个指针是相等的.

那么为什么在比较指向两个不同变量的两个指针时,我的以下代码打印为'true'?

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
}
Run Code Online (Sandbox Code Playgroud)

eva*_*nal 9

您没有比较指针本身,因为您使用'derefernce operator' *返回存储在该地址的值.在您的示例代码中,您调用了返回两个不同指针的方法.存储在每个不同地址的值恰好是1.当您取消指针时,您将获得存储在那里的值,因此您只需比较1 == 1哪个是真的.

比较指针本身你会得到假;

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
}
Run Code Online (Sandbox Code Playgroud)

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

  • 你认为比较哪些方法?他正在比较两个`*int`,两者都是1,因此在解除引用后它们是相等的. (2认同)