为什么只使用新函数创建的相同结构的两个指针在行中比较相等

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

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.