Reputation: 73
I want to compare 2 instance of the same struct to find out if it is equal, and got two different result.
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")
}
}
Upvotes: 2
Views: 448
Reputation: 42412
There are several aspects involved here:
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.
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.
Upvotes: 6