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 协议》,转载必须注明作者和本文链接
嗨,我是波波。曾经创业,有收获也有损失。我积累了丰富教学与编程经验,期待和你互动和进步! 公众号:上海 PHP 自学中心
wangchunbo
讨论数量: 2

没记错应该是要用接口断言

if value, ok := t.(string); ok {
    fmt.Println(value)
}
3年前 评论

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
}

3年前 评论

司机 @ 某医疗行业
文章
299
粉丝
345
喜欢
563
收藏
1124
排名:61
访问:12.5 万
私信
所有博文
社区赞助商