• 8.17Go之条件语句Switch


    8.17Go之条件语句Switch

    Switch简介

    Go的switch的基本功能和C、Java类似:

    • switch 语句用于基于不同条件执行不同动作,每一个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止。

    • 匹配项后面也不需要再加 break。

    特点:

    • switch 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case

    重点介绍Go当中的Switch的两个特别点:**

    • 表达式判断为true还需要执行后面的 case,可以使用 fallthrough

    • type-switch 来判断某个 interface 变量中实际存储的变量类型


    fallthrough

    特点:

    • 强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。

    示例:

    package main

    import "fmt"

    func main() {
    switch {
    case true:
    fmt.Println("1、case条件语句为false!")
    fallthrough
    case false:
    fmt.Println("2、case条件语句为true!")
    default:
    fmt.Println("默认的case")
    }
    }

    代码分析:

    • 正常来说当执行完第一条语句以后不会执行第二个case,因为第二个casefalse而且已经执行完了第一个truecase

    • fallthrough关键字存在会强制执行第二个case

    Type Switch

    特点:

    • 判断某个 interface 变量中实际存储的变量类型

    • 可以枚举类型,值类型和引用类型都可以

    语法格式:

    switch x.(type){
       case type:
          statement(s);      
       case type:
          statement(s);
       /* 你可以定义任意个数的case */
       default: /* 可选 */
          statement(s);
    }

    示例:

    package main

    import (
    "fmt"
    "go/types"
    )

    func main() {
    var inter interface{} = true

    //使用变量去代替接口当中的值并且判断类型
    switch i := inter.(type) {
    case types.Nil:
    fmt.Println("x的类型是:", i)
    case int:
    fmt.Println("x是int类型")
    case float64:
    fmt.Println("x是float64类型")
    case func(int2 int):
    fmt.Println("x是func(int)类型")
    case bool, string:
    fmt.Println("x是bool或string类型")
    default:
    fmt.Println("未知类型")
    }
    }

    可以直接判断接口当中的数据的数据类型

  • 相关阅读:
    PHP mysqli_error() 函数
    PHP mysqli_error_list() 函数
    PHP mysqli_errno() 函数
    PHP mysqli_dump_debug_info() 函数
    PHP mysqli_data_seek() 函数
    PHP mysqli_debug() 函数
    PHP mysqli_connect() 函数
    PHP mysqli_connect_errno() 函数
    PHP mysqli_connect_error() 函数
    PHP mysqli_commit() 函数
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15169309.html
Copyright © 2020-2023  润新知