To compare types using reflect, compare reflect.Type values:
var stringType = reflect.TypeOf("") // this can be declared at package-level
if reflect.TypeOf(v) == stringType {
// v has type string
}
Given an arbitrary type name X
, you can construct the type using:
var xType = reflect.TypeOf((*X)(nil)).Elem()
if reflect.TypeOf(v) == xType {
// v has type X
}
If you want to check to see if a value is some type, then use a type assertion:
if _, ok := v.(string); ok {
// v is a string
}
If you want to map types to strings, use a map keyed by reflect.Type:
var typeName = map[reflect.Type]string{
reflect.TypeOf((*int)(nil)).Elem(): "int",
reflect.TypeOf((*string)(nil)).Elem(): "string",
reflect.TypeOf((*F)(nil)).Elem(): "F",
}
...
if n, ok := typeName[reflect.TypeOf(f)]; ok {
fmt.Println(n)
} else {
fmt.Println("other")
}