golang,interface转换类型 cannot convert (type)

Golang
383
0
0
2022-04-12
标签   Golang基础

问题:

在使用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)


                }

        }


}