为什么在Go语言中,只使用new函数创建的两个相同结构的指针会比较相等?

huangapple go评论82阅读模式
英文:

why two pointer of same struct which only used new function for creating compares equal in go

问题

我想比较两个相同结构的实例,以确定它们是否相等,但得到了两个不同的结果。

  1. 将代码 // fmt.Println("%#v\n", a) 注释掉,程序输出为 "Equal"。
  2. 使用 fmt 打印变量 "a",然后得到输出 "Not Equal"。

请帮我找出原因。

我使用的是 Go 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\n", a)
    if a == b { 
        println("Equals")
    } else {
        println("Not Equals")
    }   
}
英文:

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\n", 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\n", a)
    if a == b { 
        println("Equals")
    } else {
        println("Not Equals")
    }   
}

答案1

得分: 6

这里涉及到几个方面:

  1. 通常情况下,你不能通过比较指针来比较结构体的值:ab是指向example的指针,而不是example的实例。a==b比较的是指针(即内存地址),而不是值。

  2. 不幸的是,你的example是空结构体struct{},对于唯一的空结构体来说,一切都不同,因为它实际上不存在,不占用任何空间,因此所有不同的struct {}可能(或可能不)具有相同的地址。

所有这些与调用fmt.Println无关。空结构体的特殊行为只是通过fmt.Println进行的反射而显现出来。

不要使用struct {}来测试任何真实结构体的行为。

英文:

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.

huangapple
  • 本文由 发表于 2014年10月15日 17:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/26378995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定