wangjild
wangjild

Reputation: 73

why two pointer of same struct which only used new function for creating compares equal in go

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

Upvotes: 2

Views: 448

Answers (1)

Volker
Volker

Reputation: 42412

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.

Upvotes: 6

Related Questions