Go 语言中的 switch 语句

栏目: IT技术 · 发布时间: 5年前

内容简介:正如代码清单 3-6 所示,Go 提供了代码清单 3-6执行这个程序将产生以下输出:

Go 语言中的 switch 语句

Note

本文摘录自《Go语言趣学指南》第 3 章, 请访问 gpwgcn.com 以获取更多相关信息。

Go 语言中的 switch 语句

正如代码清单 3-6 所示,Go 提供了 switch 语句,它可以将一个值和多个值进行比较。

代码清单 3-6 switch 语句: concise-switch.go

fmt.Println("There is a cavern entrance here and a path to the east.")
var command = "go inside"

switch command {    // 将命令和给定的多个分支进行比较
case "go east":
    fmt.Println("You head further up the mountain.")
case "enter cave", "go inside":     // 使用逗号分隔可选值
    fmt.Println("You find yourself in a dimly lit cavern.")
case "read sign":
    fmt.Println("The sign reads 'No Minors'.")
default:
    fmt.Println("Didn't quite get that.")
}

执行这个程序将产生以下输出:

There is a cavern entrance here and a path to the east.
You find yourself in a dimly lit cavern.

Note

除了文字以外, switch 语句还可以接受数字作为条件。

switch 的另一种用法是像 if...else 那样,在每个分支中单独设置比较条件。 正如代码清单 3-7 所示, switch 还拥有独特的 fallthrough 关键字,它可以用于执行下一分支的代码。

代码清单 3-7 switch 语句: switch.go

var room = "lake"

switch {    // 比较表达式将被放置到单独的分支里面。
case room == "cave":
    fmt.Println("You find yourself in a dimly lit cavern.")
case room == "lake":
    fmt.Println("The ice seems solid enough.")
    fallthrough    // 下降(fall through)至下一分支。
case room == "underwater":
    fmt.Println("The water is freezing cold.")
}

执行这段代码将产生以下输出:

The ice seems solid enough.
The water is freezing cold.

Note

在 C、 Java 、JavaScript 等语言中, 下降是 switch 语句各个分支的默认行为。 Go 对此采取了更为谨慎的做法, 用户需要显式地使用 fallthrough 关键字才会引发下降。


以上所述就是小编给大家介绍的《Go 语言中的 switch 语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Concepts, Techniques, and Models of Computer Programming

Concepts, Techniques, and Models of Computer Programming

Peter Van Roy、Seif Haridi / The MIT Press / 2004-2-20 / USD 78.00

This innovative text presents computer programming as a unified discipline in a way that is both practical and scientifically sound. The book focuses on techniques of lasting value and explains them p......一起来看看 《Concepts, Techniques, and Models of Computer Programming》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具