The compiler can allocate the same address for empty structs, so I
actually expected a==b to be true, not false. However, there's
something more interesting going on here because:
a := &Foo{}
b := &Foo{}
fmt.Printf("%t\n", *a == *b)
fmt.Printf("%t\n", a == b)
fmt.Printf("%p %p\n", a, b)
x := Bar(a)
y := Bar(b)
fmt.Printf("%t\n", Bar(a) == Bar(b))
fmt.Printf("%t\n", x == y)
Prints:
true
true
0x58e360 0x58e360 // Note that a and be are pointing to the same address
true
true
But:
a := &Foo{}
b := &Foo{}
fmt.Printf("%t\n", *a == *b)
fmt.Printf("%t\n", a == b)
//fmt.Printf("%p %p\n", a, b) // Comment out the print
x := Bar(a)
y := Bar(b)
fmt.Printf("%t\n", Bar(a) == Bar(b))
fmt.Printf("%t\n", x == y)
Prints:
true
false
true
true
On Thu, Feb 22, 2024 at 3:56 AM Brien Colwell <[email protected]> wrote:
>
> I'm confused by this output. It appears that the interface of two different
> pointers to an empty struct are equal. In all other cases, interface equality
> seems to be the pointer equality. What's going on in the empty struct case?
>
> ```
> package main
>
> import "fmt"
>
> type Foo struct {
> }
>
> func (self *Foo) Hello() {
> }
>
> type FooWithValue struct {
> A int
> }
>
> func (self *FooWithValue) Hello() {
> }
>
> type Bar interface {
> Hello()
> }
>
> func main() {
> a := &Foo{}
> b := &Foo{}
> fmt.Printf("%t\n", *a == *b)
> fmt.Printf("%t\n", a == b)
> fmt.Printf("%t\n", Bar(a) == Bar(b))
>
> c := &FooWithValue{A: 1}
> d := &FooWithValue{A: 1}
> fmt.Printf("%t\n", *c == *d)
> fmt.Printf("%t\n", c == d)
> fmt.Printf("%t\n", Bar(c) == Bar(d))
> }
> ```
>
> Prints (emphasis added on the strange case):
>
> ```
> true
> false
> **true**
> true
> false
> false
> ```
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/d93760c9-61a7-4a3c-9b5c-d89f023d2253n%40googlegroups.com.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/CAMV2Rqrq21ymUJ00ni_JV%3Dkv6itqZg51GoWM5zJNjcGU1BKcuA%40mail.gmail.com.