zoukankan      html  css  js  c++  java
  • 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("未知类型")
    }
    }

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

  • 相关阅读:
    085 Maximal Rectangle 最大矩形
    084 Largest Rectangle in Histogram 柱状图中最大的矩形
    083 Remove Duplicates from Sorted List 有序链表中删除重复的结点
    082 Remove Duplicates from Sorted List II 有序的链表删除重复的结点 II
    081 Search in Rotated Sorted Array II 搜索旋转排序数组 ||
    080 Remove Duplicates from Sorted Array II 从排序阵列中删除重复 II
    079 Word Search 单词搜索
    078 Subsets 子集
    bzoj2326: [HNOI2011]数学作业
    bzoj2152: 聪聪可可
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15169309.html
Copyright © 2011-2022 走看看