首页 > 其他 > 详细

从零开始学Go之接口(二):类型断言与类型选择

时间:2019-07-02 14:03:39      阅读:84      评论:0      收藏:0      [点我收藏+]

类型断言:

类型断言提供了访问接口值底层具体值的方式。

变量名 := 接口名.(判断类型名)

var i interface{} = "hello"
s := i.(string) 
//f := i.(float64) //编译错误,因为i的值不为float64

当只有一个返回值时,返回值为对应类型的值,而判断类型名与接口值类型不对应时,程序会宕机panic

此时我们需要第二种方式:

变量名,是否为判断类型名结果 := 接口名.(判断类型名)

var i interface{} = "hello"
s,ok := i.(string) 

当有两个返回值时,第一个返回值为对应类型的值,第二个返回值为布尔值,是判断接口值是否为断言的类型,而判断类型名与接口值类型不对应时,第一个值会返回为断言类型的零值,而不会产生panic

func main() {
 var i interface{}
 //s := i.(string) //panic: interface conversion: interface {} is nil, not string
 i = "string"
 s := i.(string)
 fmt.Println(s)
?
 s, ok := i.(string)
 fmt.Println(s, ok)
?
 f, ok := i.(float64)
 fmt.Println(f, ok)
?
 //f = i.(float64) // 报错(panic)
 fmt.Println(f)
}

运行结果:

string

string true

0 false

0

 

类型选择:

类型选择是对几个类型断言的分支选择结构,注意switch后的i.(具体类型)换成了i.(type)

switch v := i.(type) {

case 类型:

代码块

}

func do(i interface{}) {
 switch v := i.(type) {
 case int:
  fmt.Printf("Twice %v is %v\n", v, v*2)
 case string:
  fmt.Printf("%q is %v bytes long\n", v, len(v))
 default:
  fmt.Printf("I don‘t know about type %T!\n", v)
 }
}
?
func main() {
 do(21)
 do("hello")
 do(true)
}

运行结果:

Twice 21 is 42

"hello" is 5 bytes long

I don‘t know about type bool!

从零开始学Go之接口(二):类型断言与类型选择

原文:https://www.cnblogs.com/VingB2by/p/11119842.html

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