golang中Switch 语句详解

iXiAo9 · · 2194 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Switch 语句详解

switch 第一种表达式

func main() {
    num := 3
    switch num {
    case 1:
        fmt.Println("num=1")
    case 2:
        fmt.Println("num=2")
    case 3:
        fmt.Println("num=3")
    default:
        fmt.Print("没有条件成立")
    }
}

输出结果

API server listening at: 127.0.0.1:22973
num=3
Process exiting with code: 0

num := 3为全局变量

switch 第二种表达式

func main() {
    num := 3
    switch {
    case num <= 1:
        fmt.Println("<= 1")
    case num >= 2:
        fmt.Println(">= 2")
    case num >= 3:
        fmt.Println(">= 3")
    default:
        fmt.Print("没有条件成立")
    }
}

输出结果

API server listening at: 127.0.0.1:2079
>= 2
Process exiting with code: 0

num := 3为全局变量

我们可以添加fallthrough让case语句继续运行判断

func main() {
    num := 3
    switch {
    case num <= 1:
        fmt.Println("<= 1")
    case num >= 2:
        fmt.Println(">= 2")
        fallthrough
    case num >= 3:
        fmt.Println(">= 3")
    default:
        fmt.Print("没有条件成立")
    }
}

添加fallthrough后输出结果

API server listening at: 127.0.0.1:49351
>= 2
>= 3
Process exiting with code: 0

switch 第三种表达式

num := 3放入switch语句中

func main() {
    switch num := 3; {
    case num <= 1:
        fmt.Println("<= 1")
    case num >= 2:
        fmt.Println(">= 2")
        fallthrough
    case num >= 3:
        fmt.Println(">= 3")
    default:
        fmt.Print("没有条件成立")
    }
}

输出结果

API server listening at: 127.0.0.1:5593
>= 2
>= 3
Process exiting with code: 0

第三种输出与第二种输出结果一致

func main() {
    switch num := 3; {
    case num <= 1:
        fmt.Println("<= 1")

switch num := 3;只作用于switch语句中,我们最后添加一个输出语句查看是否能输出num的值

func main() {
    switch num := 3; {
    case num <= 1:
        fmt.Println("<= 1")
    case num >= 2:
        fmt.Println(">= 2")
        fallthrough
    case num >= 3:
        fmt.Println(">= 3")
    default:
        fmt.Print("没有条件成立")
    }
    fmt.Println(num)
}

输出结果

undefined: num

此结果证明在switch语句中声明变量为局部变量


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:iXiAo9

查看原文:golang中Switch 语句详解

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2194 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传