Golang use of .(type) outside type switch 关于参数类型

柔情痞子 提交于 2019-12-05 01:34:15

Golang 中如何获取interface参数的类型?
执行使用以下语句:

fmt.Println("type:", v.(type))

提示错误:

use of .(type) outside type switch

正确的使用方法是必须在switch case中。
举例如下:

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)


                }

        }


}

编译,执行

$ go build arm.go
$ ./arm

结果:

type:string, value: tow
type:int, value: 88
type:string, value: three

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!