There are four types of conversions in Golang, namely: assertion, explicit, implicit, and coercion. Below I will introduce each conversion usage scenario and method one by one
When the interface{} type is converted to float32 or float64 type for storage, there are relatively strict requirements for variable type conversion in Go.
type assertion
Type assertions are combined with switch to convert each type of variable
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: ("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: ("data type is:%T \n", value) return 0, value }
There are two problems with this conversion
1. It is impossible to judge the slice, and there are multiple variable values in the slice that need to be processed one by one.
2. Cannot convert multiple types of variables in a unified manner
Use reflect package for processing. The reflect package cannot recognize structure variables introduced by other packages, and needs to be combined with type assertions.
func typereflect(value interface{}) (typ int, val interface{}) { res := (value) switch () { case , reflect.Int8, reflect.Int16, reflect.Int32: return 6, float32(()) case , reflect.Uint8, reflect.Uint16, reflect.Uint32: return 6, float32(()) case reflect.Float32: return 6, float32(()) case reflect.Int64: return 10, float64(()) case reflect.Uint64: return 10, float64(()) case reflect.Float64: return 10, () case : return 3, () default: ("ohter type is:%T \n", value) switch value.(type) { case : time := value.() ("time is ", ()) } return 0, val } }
The above two methods don't feel perfect. There is no more perfect way to deal with interface{} variables in Go. Let's talk to you if you have any masters who know more about the processing methods.
This is the end of this article about the implementation example of golang interface{} type conversion. For more related golang interface{} type conversion content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!