The Go Programming Language Specification said.
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
But as following code snippet, it seems variable v1, and v3 has different type, why they can get a true output:
package main
import "fmt"
import "reflect"
type T1 struct { name string }
type T2 struct { name string }
func main() {
v1 := T1 { "foo" }
v2 := T2 { "foo" }
v3 := struct{ name string } {"foo"}
v4 := struct{ name string } {"foo"}
fmt.Println("v1: type=", reflect.TypeOf(v1), "value=", reflect.ValueOf(v1)) // v1: type= main.T1 value= {foo}
fmt.Println("v2: type=", reflect.TypeOf(v2), "value=", reflect.ValueOf(v2)) // v2: type= main.T2 value= {foo}
fmt.Println("v3: type=", reflect.TypeOf(v3), "value=", reflect.ValueOf(v3)) // v3: type= struct { name string } value= {foo}
fmt.Println("v4: type=", reflect.TypeOf(v4), "value=", reflect.ValueOf(v4)) // v4: type= struct { name string } value= {foo}
//fmt.Println(v1 == v2) // compiler error: invalid operation: v1 == v2 (mismatched types T1 and T2)
fmt.Println(v1 == v3) // true, why? their type is different
fmt.Println(v2 == v3) // true, why?
fmt.Println(v3 == v4) // true
}
It's reasonable that v1 == v2
fails with compile error because they are different type, however how to explain the v1 == v3
get a true
result, since they also have different types, one with named struct type T1
, and the other with anonymous struct.
Thanks.
Update Question based on feedback
Thanks @icza, @John Weldon for your explanation, I think this issue is resolved, I am now updating the question.
In summary, a struct is comparable if it meet following 2 specs:
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.
The 1st one is for struct type variable specific; and the 2nd one is for all types variable comparison, struct type variable is covered of course.
In my sample, the comparison variable v1 and v3 meet these two specs definition.
- All fields are comparable; in fact, the first spec define the struct rule, it focus on fields, but not struct itself, so whatever a named struct or anonymous struct, they are same rule.
- Variable v1 and v3 is assignable. (according to the rule: x's type V and T have identical underlying types and at least one of V or T is not a defined type)
So this is to explain why "v1 == v3" can get a true result. Thanks all.