I don't understand how go
compares anonymous structures. I am trying to understand this piece of code:
package main
import (
"fmt"
)
type foo struct {
bar string
}
func main() {
var x struct {
bar string
}
var y foo
fmt.Println(x == y) // this prints true
equals(x, y) // this prints false
}
func equals(a, b interface{}) {
fmt.Println(a == b)
}
Why does x == y
yields true
? They have a different type, so I would expect that they cannot be compared.
And, as they are equal, why casting them to interface{}
makes them unequal?
Why does x == y yields true?
From the Go language specification:
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
The zero-value for a string
is ""
, so x.bar
and y.bar
are equal, and therefore x
and y
are equal.
why casting them to interface{} makes them unequal?
Again, from the same page in the language specification:
Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With