Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

go

I'm quite confused about the .(type) syntax for interface variables. Is it possible to use it like this:

var a,b interface{}
// some code
if first.(type) == second.(type) {
}

or is reflect.TypeOf() the only option to check if the underlying types of a and b are the same type? What comparison am I making in the code above?

like image 364
user44168 Avatar asked Jan 15 '16 21:01

user44168


4 Answers

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.

like image 97
Eric Brown Avatar answered Oct 01 '22 01:10

Eric Brown


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.

like image 36
jacob Avatar answered Oct 01 '22 01:10

jacob


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

like image 22
Adam Smith Avatar answered Oct 01 '22 03:10

Adam Smith


Please try this:

for key, value := range data {
    switch v := value.(type) {
    case string:
        fmt.Println(key, value, "(string)")
    case float64:
        fmt.Println(key, value, "(float64)")
    case []interface{}:
        fmt.Println(key, value, "(interface)")
    }
 }

... and you can use for all types in any interface...

like image 41
Gabor725 Avatar answered Oct 01 '22 01:10

Gabor725