Go语言类型switch


switch还可以用于判断变量类型。使用方式为T.(type),即在变量后加上.(type)。见代码:

package main

 

import (

"fmt"

)

 

func main() {

var a interface{}

a = "abc"

 

switch t := a.(type) {

case string:

fmt.Printf("string %s\n", t)

case int:

fmt.Printf("int %d\n", t)

default:

fmt.Printf("unexpected type %T", t)

}

}

 

输出结果为:

string abc

 

如果将上面的:

var a interface{}

a = "abc"

这两句,合成一句:

a := "abc"

 

编译就会出错:

cannot type switch on non-interface value a (type string)

不能在一个非接口类型的变量上使用type switch。

也就是说 type switch只能用于接口的变量。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM