Golang 类型判断:type-switch
warning:
这篇文章距离上次修改已过418天,其中的内容可能已经有所变动。
在Golang中,type-switch是一种控制流语句,用于判断interface变量中实际存储的变量类型。这在处理interface{}类型的变量时非常有用。
以下是一个简单的Golang type-switch的例子:
func DoTypeSwitch(v interface{}) {
switch v := v.(type) {
case int:
fmt.Printf("v is an int with value %v\n", v)
case string:
fmt.Printf("v is a string with value %v\n", v)
case bool:
fmt.Printf("v is a bool with value %v\n", v)
default:
fmt.Printf("v is of a different type\n")
}
}
func main() {
DoTypeSwitch(10)
DoTypeSwitch("Hello, World!")
DoTypeSwitch(true)
DoTypeSwitch(3.14)
}在这个例子中,DoTypeSwitch函数接收一个interface{}类型的参数,然后使用type-switch来判断该参数的实际类型。根据不同的类型,函数打印出相应的信息。在main函数中,我们调用DoTypeSwitch函数并传入不同类型的参数,以此来测试这个type-switch。
评论已关闭