zoukankan      html  css  js  c++  java
  • Go断言

    golang的语言中提供了断言的功能。golang中的所有程序都实现了interface{}的接口,这意味着,所有的类型如string,int,int64甚至是自定义的struct类型都就此拥有了interface{}的接口,这种做法和java中的Object类型比较类似。那么在一个数据通过func funcName(interface{})的方式传进来的时候,也就意味着这个参数被自动的转为interface{}的类型。

    func funcName(a interface{}) string {
        //强制将interface{}类型转换为string类型 编译器可能会报错误cannot convert a (type interface{}) to type string: need type assertion
         return string(a)
    }
    

    所以转换过程需要类型断言,类型断言有以下几种形式:

    1、直接断言使用

    var a interface{}
    fmt.Println("Where are you,Jonny?", a.(string))
    

    但是如果断言失败一般会导致panic的发生。所以为了防止panic的发生,我们需要在断言前进行一定的判断

    2、直接断言使用

    value, ok := a.(string)
    

    如果断言失败,那么ok的值将会是false,但是如果断言成功ok的值将会是true,同时value将会得到所期待的正确的值。示例:

    value, ok := a.(string)
    if !ok {
        fmt.Println("It's not ok for type string")
        return
    }
    fmt.Println("The value is ", value)
    

    3、配合switch语句进行判断:

    var t interface{}
    t = functionOfSomeType()
    switch t := t.(type) {
    default:
        fmt.Printf("unexpected type %T", t)       // %T prints whatever type t has
    case bool:
        fmt.Printf("boolean %t
    ", t)             // t has type bool
    case int:
        fmt.Printf("integer %d
    ", t)             // t has type int
    case *bool:
        fmt.Printf("pointer to boolean %t
    ", *t) // t has type *bool
    case *int:
        fmt.Printf("pointer to integer %d
    ", *t) // t has type *int
    }
    
  • 相关阅读:
    CentOS 6.3下Samba服务器的安装与配置(转)
    利用香蕉派自制电视盒子
    利用arduino制作瓦力万年历-1.0
    arduino:int & double 转string 适合12864下使用
    centos 6.X下建立arduino开发环境
    树莓派学习笔记(7):利用bypy实现树莓派NAS同步百度云
    直接插入排序
    直接选择排序
    快速排序算法
    git 分支管理 推送本地分支到远程分支等
  • 原文地址:https://www.cnblogs.com/promenader/p/9875866.html
Copyright © 2011-2022 走看看