switch结构

switch结构介绍

  • switch也属于条件判断的语句

  • 支持多种写法,和if .. else if ...else 结构的功能类似,但是里面的细节需要注意的地方更多

  • switch基本语法

switch [定义变量;] [变量]{
  case [条件/具体值]:
      //代码
  case [条件/具体值]:
      //代码
  default:
    //代码
}
  • switch每个case分支默认只执行一个且是从上向下执行

  • default上下位置没有影响,当且仅当所有case都不成立时才执行default

switch用法(一)

  • 当变量只有固定的几个值时可以使用switch结构

复制代码
func main() {
    num := 16
    switch num {
    case 2:
        fmt.Println("2进制")
    case 8:
        fmt.Println("8进制")
    case 10:
        fmt.Println("10进制")
    case 16:
        fmt.Println("16进制")
    default:
        fmt.Println("内容不正确")
    }
    fmt.Println("程序结束")
}
复制代码
  • switch也支持在条件位置定义变量,变量有效范围为当前switch
复制代码
func main() {
    switch num := 16; num {
    case 2:
        fmt.Println("2进制")
    case 8:
        fmt.Println("8进制")
    case 10:
        fmt.Println("10进制")
    case 16:
        fmt.Println("16进制")
    default:
        fmt.Println("内容不正确")
    }
    fmt.Println("程序结束")
}
复制代码

switch用法(二)

  • 当条件是范围而不是固定值时

复制代码
func main() {
    score := 71
    switch {
    case score >= 90:
        fmt.Println("优秀")
    case score >= 80:
        fmt.Println("良好")
    case score >= 70:
        fmt.Println("中等")
    case score >= 60:
        fmt.Println("及格")
    default:
        fmt.Println("不及格")
    }
    fmt.Println("程序结束")
}
复制代码

switch用法(三)

  • case条件支持多个值,每个值使用逗号分开

复制代码
func main() {
    month := 5
    switch month {
    case 1, 3, 5, 7, 8, 10, 12:
        fmt.Println("31天")
    case 2:
        fmt.Println("28或29天")
    default:
        fmt.Println("30天")
    }
    fmt.Println("程序结束")
}
复制代码

穿透和中断

  • switch结构中某个最多只能执行一个case,使用fallthrough可以让下一个case/default继续执行

复制代码
func main() {
    switch num := 1; num {
    case 1:
        fmt.Println("1")
        fallthrough
    case 2:
        fmt.Println("2")
    case 3:
        fmt.Println("3")
        fallthrough
    case 4:
        fmt.Println("4")
    default:
        fmt.Println("不是1,2,3,4")
    }
    fmt.Println("程序结束")
}
复制代码
  • break可以用在switch和循环中,表示立即结束,无论当前结构后面还有多少代码
复制代码
func main() {
    switch num := 1; num {
    case 1:
        fmt.Println("1")
        break
        fmt.Println("break后面代码都不执行")
        fallthrough
    case 2:
        fmt.Println("2")
    case 3:
        fmt.Println("3")
        fallthrough
    case 4:
        fmt.Println("4")
    default:
        fmt.Println("不是1,2,3,4")
    }
    fmt.Println("程序结束")
}
复制代码

posted on   不要挡着我晒太阳  阅读(842)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示