Home > Enterprise >  Get switch type case to int64 - Golang
Get switch type case to int64 - Golang

Time:12-24

how can i get type switching for an empty interface to an int64

var vari interface{}
vari = 7466
switch v := vari.(type) {
case int64:
    fmt.Println("integer", v)
default:
    fmt.Println("unknown")
}

This prints unknown. It works fine (prints "integer 7466") if i do it for int but not for int64. How can i get int64?

CodePudding user response:

The literal 7466 is an untyped constant, and in that context, it is interpreted as an int, not as an int64. So either test the case for int, or do:

vari = int64(7466)

This is because int and int64 are distinct types.

CodePudding user response:

There are two cases to consider here:

  1. You absolutely know that the value assigned to the interface has some known integer type. Example:

     var vari interface{}
     vari = 7466 // could be int64|32|16|8(7466)
     v, ok := vari.(int) // or int64|32|16|8
     if !ok {
         fmt.Println("unknown")
         return 0
     }
     return int64(v)
    
  2. You don't know what the type of the value in the interface is. The reflect package might help you. Playground

     func getInt64(v interface{}) (int64, error) {
         switch reflect.TypeOf(v).Kind() {
         case reflect.Int8:
             d, _ := v.(int8)
             return int64(d), nil
         case reflect.Int16:
             d, _ := v.(int16)
             return int64(d), nil
         case reflect.Int32:
             d, _ := v.(int32)
             return int64(d), nil
         case reflect.Int64:
             d, _ := v.(int64)
             return d, nil
         case reflect.Int:
             d, _ := v.(int)
             return int64(d), nil
         // ... tackle uint if needed
         }
    
         return 0, fmt.Errorf("not interger: %v", v)
     }
    
  • Related