SoFunction
Updated on 2025-03-05

How to get the type of a variable

Just use the TypeOf method of reflect

((var)) 

Supplement: Three ways to get variable types

Using string formatting

func typeof(v interface{}) string {
    return ("%T", v)
}

Using reflect package

func typeof(v interface{}) string {
    return (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"
    }
}

Supplement: golang gets the string format of variable types List variable types

((var))  
switch xxx.(type){
  case int:....
  case float32:...
  case float64:...
  case string:...
}

For type enumeration, fallthrough cannot be used, and float32 and float64 are two different types (there is no separate float type), but int contains int64

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.