Reputation: 79
I try to use "reflect" and "(type)"
var a float64 = 6.0
if reflect.TypeOf(a) == float64 {
fmt.Printf("%T", a)
}
switch a.(type) {
case float64:
fmt.Printf("%T", a)
}
but both returned errors
error 1: type float64 is not an expression
error 2: cannot type switch on non-interface value a (type float64)
Upvotes: 0
Views: 88
Reputation: 417412
An if
statement can only compare to a single type because it doesn't have branches like the switch
statement, and you have to use a type assertion in an if
statement like this:
var i interface{}
i = 3.3 // store a float64 value in i
if f, ok := i.(float64); ok {
fmt.Print("It's a float64 value: %.2f", f)
} else {
fmt.Println("Not float64")
}
This will output (try it on the Go Playground):
It's a float64 value: 3.30
You could use reflection too, but type assertion here is more efficient and more idiomatic. For reference, this is how using reflection would look like:
if reflect.TypeOf(i) == reflect.TypeOf(float64(0)) {
fmt.Printf("It's a float64 value: %.2f", i)
} else {
fmt.Println("Not float64")
}
Output is the same. Try this one on the Go Playground.
Note that when we used type assertion, we had a variable f
of the asserted type (float64
) so we could use it if some function would require a value of that type directly. When using reflection, we did not have a value of such type, i
is "still" of type interface{}
, we could use it because fmt.Printf()
takes values of interface{}
. But if we would have to pass it to a function that requires float64
, we would still need to use (an additional) type assertion, like in the first example.
Also note that using type assertion and a type switch only makes sense if your input is an interface type, because only interface types may store values of different / multiple concrete types.
Using type assertion or type switch on a concrete type (like float64
value in your example) makes no sense becase that value may only be of type float64
and nothing else, so the language spec doesn't allow it in the first place.
Upvotes: 2