Can I compare variable types with .(type) in Golang?

someInterface.(type) is only used in type switches. In fact if you tried to run that you'd see that in the error message.

func main() {
    var a, b interface{}
    a = 1
    b = 1

    fmt.Println(a.(type) == b.(type))
}

prog.go:10: use of .(type) outside type switch

What you could do instead is a.(int) == b.(int), which is really no different from int(a) == int(b)

func main() {
    var a, b interface{}
    a = 1
    b = 1

    fmt.Println(a.(int) == b.(int))
}

true


func isType(a, b interface{}) bool {
    return fmt.Sprintf("%T", a) == fmt.Sprintf("%T", b)
}

The "%T" fmt option uses reflection under the hood, which would make the above statement practically that same as:

func isType(a, b interface{}) bool {
    return reflect.TypeOf(a) == reflect.TypeOf(b)
}

Either one would work, and won't cause a panic trying to utilize any kind of type assertion like some of the other suggestions.


You'd need to specify the type. That syntax is used to make type assertions about interfaces, not about checking the specific type. You'll have to use reflect.TypeOf for that.

You can view this answer for a proper use of type assertions.

Tags:

Types

Go