zoukankan      html  css  js  c++  java
  • switch语句

    定义

    switch 是一个条件语句,用于将表达式的值与可能匹配的选项列表进行比较,并根据匹配情况执行相应的代码块。它可以被认为是替代多个 if else 子句的常用方式。

    用法

    1.基本用法

    package main
    
    import "fmt"
    
    func main() {
        a:=10
        switch a {
        case 1:
            fmt.Println("1")
        case 2:
            fmt.Println("2")
        case 10:
            fmt.Println("10")  //因为a=10所以会打印此处结果
        
        }

    2.default(默认值)

    package main
    
    import "fmt"
    
    func main() {
        a:=11
        switch a {
        case 1:
            fmt.Println("1")
        case 2:
            fmt.Println("2")
        case 10:
            fmt.Println("10")
        default:
            fmt.Println("不知道")  //a=11,不属于以上任何一个,打印结果为默认值
        }

    3.多值匹配

    package main
    
    import "fmt"
    
    func main() {
        a:=11
        switch a {
        case 1,4,5:
            fmt.Println("1")
        case 2,8,9:
            fmt.Println("2")
        case 10,11:
            fmt.Println("10")  // a=11,当中有11的就可以会打印结果
        default:
            fmt.Println("不知道")
        }

    4.无表达式

    package main
    
    import "fmt"
    
    func main() {
        a:=11
        switch {
        case a>10:
            fmt.Println("大于10")
        case a<10:
            fmt.Println("小于10")
        default:
            fmt.Println("10")
        }

    6.穿透(fallthrough)

    package main
    
    import "fmt"
    
    func main() {
    
        a:=10
        switch a {
        case 1:
            fmt.Println("1")
            fmt.Println("xxxx")
        case 2:
            fmt.Println("2")
        case 10:
            fmt.Println("10")
            //穿透,无条件执行下一个case的内容
            fallthrough
        case 11:
            fmt.Println("11")
            test5()
            fallthrough
        case 12:
            fmt.Println("12")
        }
    }
  • 相关阅读:
    指针常量 和 常量指针
    串口通讯
    C语言的抽象与函数指针2
    STM32 中常见错误 的处理方法
    串行通信之狂扯篇
    VMware中虚拟机网卡的四种模式
    VSFTP配置虚拟用户
    MySQL数据库备份命令
    rsync Linux系统下的数据镜像备份工具
    linux常用命令
  • 原文地址:https://www.cnblogs.com/xiongying4/p/12017137.html
Copyright © 2011-2022 走看看