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自学中心 付费知识星球:破解面试:程序员的求职导师
讨论数量: 2

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

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

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
}

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
司机 @ 欣昊玉
文章
273
粉丝
339
喜欢
558
收藏
1106
排名:64
访问:12.2 万
私信
所有博文
社区赞助商