Problem
How do I find the type of an object in Go? In Python, I just use typeof
to fetch the type of object. Similarly in Go, is there a way to implement the same ?
I found 3 ways to return a variable’s type at runtime:
Using string formatting:
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
Using reflect package
func typeof(v interface{}) string {
return reflect.TypeOf(v).String()
}
Using type assertions
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case float64:
return "float64"
//... etc
default:
return "unknown"
}
}
Every method has a different best use case:
- string formatting – short and low footprint (not necessary to import reflect package)
- reflect package – when need more details about the type we have access to the full reflection capabilities
- type assertions – allows grouping types, for example recognize all int32, int64, uint32, uint64 types as “int”