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

类型断言:

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

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

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!

转载于:https://www.cnblogs.com/VingB2by/p/11119842.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值