zoukankan      html  css  js  c++  java
  • [Go] ok 判断 汇总

    1、判断 类型

    类似于 JavaScript 中 typeof 和 Java 中 instanceof

    var a interface{}
    newA, ok := a.(string)
    // 如果 ok 是 true,则说明 变量 a 是字符串类型,而 newA 就是 string 类型的变量,a 的实际值
    //
    

    2、判断 key 是否在 map 中

    var nameList = map[string]string{"姓名": "李四", "性别": "男"}
    name, ok := nameList["姓名"] // 假如 key 存在,则 ok = true,否则,ok = false
    if ok {
      fmt.Println(name)
    }

    3、判断 channel 是否 已关闭 且 没有数据

    for {
        x, ok := <-chantest
        if !ok {
            break // 通道 已关闭 且 没有数据,则跳出循环
        }
    }
    

    温馨提示:

    判断类型,还有另外一种方式:和 switch 结合

    var v interface{}
    // 省略了部分代码
    // v = 8
    // v = "wenjianbao"
    
    switch i := v.(type) {
    case string:
        fmt.Printf("The string is '%s'
    ", i)
    case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64:
        fmt.Printf("The interger is %d
    ", i)
    default:
        fmt.Printf("Unsupporte value.(type=%T)
    ", i)
    }

    这里的 i := v.(type) 使经类型转换后的值得以保存。i 的类型一定会是 v 的值的实际类型。

    详情:http://www.cnblogs.com/52php/p/6391537.html

  • 相关阅读:
    java类,接口浅谈
    人月神话阅读笔记01
    学习进度条14
    学习进度条13
    每日站立会议10(完结)
    每日站立会议09
    每日站立会议08
    构建之法阅读笔记06(完)
    每日站立会议07
    每日站立会议06
  • 原文地址:https://www.cnblogs.com/52php/p/6789028.html
Copyright © 2011-2022 走看看