Some of the existing answers on here about how to determine the type of an object at runtime..god help us
if reflect.TypeOf(err) == string {
}
that doesn't compile
if reflect.TypeOf(err) == "string" {
}
neither does that or this:
if reflect.TypeOf(err).Kind() == "string" {
}
how do we do this?
If I use the typeof function given by one of the answers, I get:
Compare like string
if reflect.TypeOf(err).String() == "string" {
fmt.Println("hello")
}
Or using type assertions
type F = func()
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
case F:
return "F"
//... etc
default:
return "unknown"
}
}
Then
var f F
if typeof(f) == "F"{
fmt.Println("hello F")
}
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")
}