• 从零开始学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
    ", v, v*2)
     case string:
      fmt.Printf("%q is %v bytes long
    ", v, len(v))
     default:
      fmt.Printf("I don't know about type %T!
    ", 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!

  • 相关阅读:
    for() 和$.each()的用法区别
    HTML5 UTF-8 中文乱码
    chrome,opera..通过file协议浏览html代码时,发送的ajax请求本地文件,会报跨域错误
    局部方法$("html").load()和全局方法$.get()、$.post()
    iOS开发--动画篇之layout动画深入
    iOS 开发--转场动画
    iOS开发--泛型
    Python十分钟学会
    iOS 开发--动画
    一个简单的ObjC和JavaScript交互工具
  • 原文地址:https://www.cnblogs.com/VingB2by/p/11119842.html
Copyright © 2020-2023  润新知