pointers - 在 Go 中比较指针

标签 pointers go

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

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

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
}

最佳答案

您没有比较指针本身,因为您使用了“取消引用运算符”*,它返回存储在该地址的值。在您的示例代码中,您调用了返回两个不同指针的方法。存储在每个不同地址的值恰好是 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
}

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

关于pointers - 在 Go 中比较指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276205/

相关文章:

C++ 指针 : changing the contents without changing the address?

c - 指向矩阵

arrays - 复制相同类型的数组

go - 在 Go 中查看优先队列的顶部?

Go 编译已声明但未使用

c++ - 将成员函数作为成员函数的参数传递

objective-c - 在Objective-C中使用指针式分配与 setter 方法有多危险?

google-app-engine - API 错误 1 ​​(datastore_v3 : BAD_REQUEST): ApplicationError: 1 app "id1" cannot access app "id2"'s data

objective-c - 如何在 Swift 中创建指向自身的静态指针变量?

go - 如何高效实现json tcp server并防止socket flood?