golang interface{}类型转换的实现示例
作者:快刀一哥
在Go语言中,类型转换可以通过断言、显式、隐式和强制四种方式实现,针对interface{}类型转换为float32或float64,需要使用type断言或reflect包处理,感兴趣的可以了解一下
Golang中存在4种类型转换,分别是:断言、显式、隐式、强制。下面我将一一介绍每种转换使用场景和方法
遇到interface{}类型转换成float32 或者 float64类型进行存储,go中对变量类型转换有比较严格要求。
type断言
type断言配合switch 对每种类型的变量进行转换
func TpyeTransfer(value interface{}) (typ int, val interface{}) {
switch value.(type) {
case int:
return 6, float32(value.(int))
case bool:
return 3, value.(bool)
case int8:
return 6, float32(value.(int8))
case int16:
return 6, float32(value.(int16))
case int32:
return 6, float32(value.(int32))
case uint8:
return 6, float32(value.(uint8))
case uint16:
return 6, float32(value.(uint16))
case uint32:
return 6, float32(value.(uint32))
case float32:
return 6, float32(value.(float32))
case string:
fmt.Printf("data type string is %T \n", value)
return 0, value
case int64:
return 10, float64(value.(int64))
case float64:
return 10, float64(value.(float64))
case uint64:
return 10, float64(value.(uint64))
default:
fmt.Printf("data type is:%T \n", value)
return 0, value
}
这样转换有两个问题
1.对切片无法判断,切片有多个变量数值需要逐个处理
2.不能对多个类型的变量进行统一转换
reflect.TypeOf
利用reflect包进行处理,reflect包不能识别time.Time等其他包引入的结构体变量,需要和type断言组合使用
func typereflect(value interface{}) (typ int, val interface{}) {
res := reflect.ValueOf(value)
switch res.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return 6, float32(res.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return 6, float32(res.Uint())
case reflect.Float32:
return 6, float32(res.Float())
case reflect.Int64:
return 10, float64(res.Int())
case reflect.Uint64:
return 10, float64(res.Uint())
case reflect.Float64:
return 10, res.Float()
case reflect.Bool:
return 3, res.Bool()
default:
fmt.Printf("ohter type is:%T \n", value)
switch value.(type) {
case time.Time:
time := value.(time.Time)
fmt.Println("time is ", time.Unix())
}
return 0, val
}
}
如上两种方法感觉都不完美,在go中还没有赵傲比较完美的处理interface{}变量的方法,有了解更多处理方法的大神一起交流一下
到此这篇关于golang interface{}类型转换的实现示例的文章就介绍到这了,更多相关golang interface{}类型转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
