douchao1957 2017-01-25 21:52
浏览 42
已采纳

为什么这些golang指针不相等?

In the example below I check the equality of two pointers

  • The pointers are pointing to the same address
  • They are not the same pointer

How do I check if two pointers are pointing to the same address? I do not want to check if the contents of both pointers are equal.

package main

import (
    "fmt"
)

type Map struct {}
type Fragment struct {
    Map *Map
}

func (m1 Map) NewFragment() (f Fragment) {
    f.Map = &m1
    return
}


var m Map = Map {}

func main() {
    f := m.NewFragment()
    fmt.Println(f.Map == &m) // false
    fmt.Println(*f.Map == m) // true

}

Go Playground

  • 写回答

2条回答 默认 最新

  • duanjiwei1283 2017-01-26 02:19
    关注

    As JimB answered, you can use == to compare pointers. The reason this program behaves that way is because when you call the NewFragment method, a copy is made of the receiver. In this case, that means the line f.Map = &m1 is taking the address of the copy, not the original object. Therefore, the pointers are different (f.Map != &m), and the values are the same (*f.Map == m).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler