dthp96899 2014-10-15 09:27
浏览 40
已采纳

为什么只使用新函数创建的相同结构的两个指针在行中比较相等

I want to compare 2 instance of the same struct to find out if it is equal, and got two different result.

  1. comment the code // fmt.Println("%#v ", a), the program output is "Equal"
  2. Use the fmt to print variable "a", then I got the output "Not Equal"

Please help me to find out Why???

I use golang 1.2.1

package main

import (
    "fmt"
)

type example struct {
}

func init() {
   _ = fmt.Printf
}

func main() {

    a := new(example)
    b := new(example)

    // fmt.Println("%#v
", a)
    if a == b { 
        println("Equals")
    } else {
        println("Not Equals")
    }   
}
  • 写回答

1条回答 默认 最新

  • douxieti6851 2014-10-15 09:50
    关注

    There are several aspects involved here:

    1. You generally cannot compare the value of a struct by comparing the pointers: a and b are pointers to example not instances of example. a==b compares the pointers (i.e. the memory address) not the values.

    2. Unfortunately your example is the empty struct struct{} and everything is different for the one and only empty struct in the sense that it does not really exist as it occupies no space and thus all different struct {} may (or may not) have the same address.

    All this has nothing to do with calling fmt.Println. The special behavior of the empty struct just manifests itself through the reflection done by fmt.Println.

    Just do not use struct {} to test how any real struct would behave.

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

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题