golang,interface转换类型 cannot convert t (typ
问题:#
在使用 interface 表示任何类型时,如果要将 interface 转为某一类型,直接强制转换是不行的,例如:
var t interface{} = "abc"
s := string(t)
cannot convert t(type interface {}) to type string: need type assertion
这样是不行的,需要进行 type assertion 类型断言,具体使用方法请参考:
golang 任何类型 interface {}
解决#
package main
import (
"fmt"
)
func main() {
CheckType("tow", 88, "three")
}
func CheckType(args ...interface{}) {
for _,v := range args {
switch v.(type) {
case int:
fmt.Println("type:int, value:", v)
case string:
fmt.Println("type:string, value:", v)
default:
fmt.Println("type:unkown,value:",v)
}
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
没记错应该是要用接口断言
func ValueInterfaceToString(value interface{}) string {
var key string
if value == nil {
return key
}
switch value.(type) {
case float64:
ft := value.(float64)
key = strconv.FormatFloat(ft, ‘f’, -1, 64)
case float32:
ft := value.(float32)
key = strconv.FormatFloat(float64(ft), ‘f’, -1, 64)
case int:
it := value.(int)
key = strconv.Itoa(it)
case uint:
it := value.(uint)
key = strconv.Itoa(int(it))
case int8:
it := value.(int8)
key = strconv.Itoa(int(it))
case uint8:
it := value.(uint8)
key = strconv.Itoa(int(it))
case int16:
it := value.(int16)
key = strconv.Itoa(int(it))
case uint16:
it := value.(uint16)
key = strconv.Itoa(int(it))
case int32:
it := value.(int32)
key = strconv.Itoa(int(it))
case uint32:
it := value.(uint32)
key = strconv.Itoa(int(it))
case int64:
it := value.(int64)
key = strconv.FormatInt(it, 10)
case uint64:
it := value.(uint64)
key = strconv.FormatUint(it, 10)
case string:
key = value.(string)
case []byte:
key = string(value.([]byte))
default:
newValue, _ := json.Marshal(value)
key = string(newValue)
}
return key
}