英文:
why two pointer of same struct which only used new function for creating compares equal in go
问题
我想比较两个相同结构的实例,以确定它们是否相等,但得到了两个不同的结果。
- 将代码 // fmt.Println("%#v\n", a) 注释掉,程序输出为 "Equal"。
- 使用 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.
- comment the code // fmt.Println("%#v\n", a), the program output is "Equal"
- 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
这里涉及到几个方面:
-
通常情况下,你不能通过比较指针来比较结构体的值:
a
和b
是指向example
的指针,而不是example
的实例。a==b
比较的是指针(即内存地址),而不是值。 -
不幸的是,你的
example
是空结构体struct{}
,对于唯一的空结构体来说,一切都不同,因为它实际上不存在,不占用任何空间,因此所有不同的struct {}
可能(或可能不)具有相同的地址。
所有这些与调用fmt.Println
无关。空结构体的特殊行为只是通过fmt.Println
进行的反射而显现出来。
不要使用struct {}
来测试任何真实结构体的行为。
英文:
There are several aspects involved here:
-
You generally cannot compare the value of a struct by comparing the pointers:
a
andb
are pointers toexample
not instances of example.a==b
compares the pointers (i.e. the memory address) not the values. -
Unfortunately your
example
is the empty structstruct{}
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 differentstruct {}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论