if-else语句
Golang的if-else语句比较简单,值得注意的有两点: 1.条件语句不需要用括号括起来
2.if-else语句的写法,else关键字必须在if语句大括号的后面,原因是Golang会自动插入分号,具体看以下示例
// 错误示范:else关键字没有在if语句大括号的后面
func errorWriting(num int) {
if num > 1 {
fmt.Println("num more than 1")
}; // 相当于在这里加了分号
else{
fmt.Println("num less than 1")
}
}
// 正确示范
func correctWriting(num int) {
if num > 1 {
fmt.Println("num more than 1")
} else{
fmt.Println("num less than 1")
}
}
3.同for循环一样,if语句可以在条件表达式前执行一个简单的语句,该语句声明的变量的作用域仅局限在if-else中,减少变量的误用。
For循环
对于Go来说,只有一种循环结构,即For循环。对于其他语言,除了for循环,还包括while循环和do...while循环,不过这并代表这些不能用for循环实现。
1.for循环形式一(最常见)
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
2.for循环形式二(遍历元素)
func iterElements() {
list := []int{1, 2, 3}
for index, num := range list{
fmt.Println("索引", index)
fmt.Println("元素", num)
}
// 由于一般比较少用到索引,所以会用"_"代替
for _, num := range list {
fmt.Println("元素", num)
}
}
3.for循环形式三(实现while循环)
func achieveWhileByFor(num int) {
for num > 0 {
num --
fmt.Println(num)
}
}
4.for循环形式四(死循环)
func achieveInfiniteLoop(num int) {
for {
num --
if num < 0 {
fmt.Println(num)
break
}
}
}
switch语句
其实很多人发现,我们在程序中并不常用switch语句,并往往使用if-else语句代替,其中原因我大概猜想如下:
- 经常容易漏加
break语句,导致程序执行了所有case语句 - switch的case语句只能加常量,如果你用C语言编写的话,甚至只能用int类型作为判断条件
对于上面的两个问题,if-else语句能够完美解决,只不过写法从感官上没有switch语句那么直接,所以何乐而不为呢?
不过对于Golang来说,它的switch跟以往的语言不太一样,并没有上述的两个问题,所以对于有强迫症的人,switch也许是一种代替if-else语句的方式。
1.Golang对自动在case语句后面加上break语句,所以并不用担心漏加的问题
// 比如你的电脑是darwin,程序只会打印"OS X.",而不会执行其他语句
func judgeOs(){
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd, windows...
fmt.Printf("%s.\n", os)
}
}
2.如果你不要golang给你自动加的break语句,想要其他语言的效果,可以加fallthrough解决
func number() int {
num := 15 * 5
return num
}
// fallthrough 语句应该是 case 子句的最后一个语句。如果它出现在了 case 语句的中间,编译器将会报错
func withoutBreak() {
switch num := number(); { // num is not a constant
case num < 50:
fmt.Printf("%d is lesser than 50\n", num)
fallthrough
case num < 100:
fmt.Printf("%d is lesser than 100\n", num)
fallthrough
case num < 200:
fmt.Printf("%d is lesser than 200", num)
}
}
3.switch的case语句可以是表达式,不只是常量
// 下面这种形式可以代替if-else语句
// 没有条件的switch相当于 switch true
func ifElseReplace() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
4.type switch,即通过switch语句判断interface{}的数据类型
func judgeTypeTest(args ...interface{}) {
for _, arg := range args{
// 无法使用if-else语句代替,大家可以试试
switch arg.(type){
case int:
fmt.Println("type is int")
case string:
fmt.Println("type is string")
default:
fmt.Println("unknown type")
}
}
}
为什么不喜欢用switch,而是用if..else? studygolang.com/articles/23…
select 语句
推荐阅读:
1.select关键字用法: www.jianshu.com/p/2a1146dc4…
2.select关键字典型用法: yanyiwu.com/work/2014/1…