Skip to content

Goのreflectで同じ型かどうかを検査する

以下のようなコードがあった場合、

v1 := reflect.Value(s1)
v2 := reflect.Value("hello")

v1v2が同じ型かどうかを検査するには、単純に reflect.Type を比較すればいい。

v1.Type() == v2.Type()

これはreflect.Typeのドキュメントで保証されている。

Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.