Say I have the following code:
var x interface{}
y := 4
x = y
fmt.Println(reflect.TypeOf(x))
This will print int as the type. My question is how can I test for the type? I know there is the type switch which does this, so I could do:
switch x.(type) {
case int:
fmt.Println("This is an int")
}
But if I only want to check for just one specific type the switch seems like the wrong tool. Is there a more direct method of doing this like
reflect.TypeOf(x) == int
or is the type switch the way to go?
Type assertions return two values .. the first is the converted value, the second is a bool indicating if the type assertion worked properly.
So you could do this:
_, ok := x.(int)
if ok {
fmt.Println("Its an int")
} else {
fmt.Println("Its NOT an int")
}
..or, shorthand:
if _, ok := x.(int); ok {
fmt.Println("Its an int")
}
I just figured out another way of doing this based on this:
if _, ok := x.(int); ok {
fmt.Println("This is an int")
}
In Effective Go you can find a really simple example of what you're trying to achieve.
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t
", t) // t has type bool
case int:
fmt.Printf("integer %d
", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t
", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d
", *t) // t has type *int
}
If you have a single type that you have to check, use a simple if, otherwise use a switch for better readability.