首页 > 编程语言 > 详细

Go语言类型switch

时间:2015-03-07 22:31:39      阅读:315      评论:0      收藏:0      [点我收藏+]

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只能用于接口的变量。

Go语言类型switch

原文:http://www.cnblogs.com/baiyuxiong/p/4320963.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!