I'm trying to understand how to check if two objects are the same when they implement the same interface.
Here is the example code:
package main
import (
"fmt"
)
type shout interface {
echo()
}
type a struct {}
func (*a) echo () {
fmt.Println("a")
}
type b struct {}
func (*b) echo () {
fmt.Println("b")
}
func compare(a, b shout) {
//fmt.Println(&a, &b)
if a == b {
fmt.Println("same")
} else {
fmt.Println("not same")
}
}
func main() {
a1 := &a{}
b1 := &b{}
a2 := &a{}
a1.echo()
b1.echo()
compare(a1, b1)
compare(a1, a2)
compare(a1, a1)
}
https://play.golang.org/p/qo9XnbthMw
The result is:
not same
not same
same
a1 and a2 are not the same
But if uncomment the line#22
fmt.Println(&a, &b)
The result is:
0x1040a120 0x1040a128
not same
0x1040a140 0x1040a148
same
0x1040a158 0x1040a160
same
Does anyone can figure out what happened here? Does the Golang compiler optimize something?
Thanks