0

Here is my code:

package main

import (
    "fmt"
)

type A struct{}

func main() {
    var ad, bd A
    res1 := &ad == &bd
    res2 := ad == bd
    fmt.Println(res1, res2)// true true
    fmt.Printf("%p, %p\n", &ad, &bd) // 0x57bb60, 0x57bb60
}

Now if I comment the last line of main function like this:

package main

import (
    "fmt"
)

type A struct{}

func main() {
    var ad, bd A
    res1 := &ad == &bd
    res2 := ad == bd
    fmt.Println(res1, res2) // false true
    //fmt.Printf("%p, %p\n", &ad, &bd)
}

The program prints false true!

How can the last line influence the output? Is there any special feature with the empty struct? Or this problem is caused by the compiler?

guning
  • 21
  • 3
  • 4
    Empty structs are zero-sized, and per the spec _may_ be placed at the same memory location. Printing its address may influence where it's placed since that may make the value escape to heap. – icza Jun 02 '20 at 15:54
  • Nobody uses empty structs except for simulating set types for really _very_ **large** sets (or because people want to be clever). – Volker Jun 02 '20 at 20:10

0 Answers0