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{}类型转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论