Reputation: 247
I want to be able to compare the type of an object using reflect
. Here is my code:
package main
import (
"fmt"
"reflect"
)
func main() {
tst := "cat"
if reflect.TypeOf(tst) == string {
fmt.Println("It's a string!")
}
}
This gives me an error type string is not an expression
. How can I fix this only using reflect? (no type switches, etc.)
Upvotes: 2
Views: 305
Reputation: 49187
Two simple options:
use Kind
:
if reflect.TypeOf(tst).Kind() == reflect.String {
fmt.Println("It's a string!")
}
use TypeOf
another string:
if reflect.TypeOf(tst) == reflect.TypeOf("") {
fmt.Println("It's a string!")
}
However, personally I'd prefer a type switch or type check (i.e. if _, ok := tst.(string); ok {...}
Upvotes: 2