Go语言学习记录3——条件和循环语句

一. 条件语句

go语言的循环语句长得像这样:
注意else要和 { 在同一行

if condition {  
} else if condition {
} else {
}
//or
if condition {  
}

除了这样,还有先执行statement再判断condition的语句

if statement; condition {  
}

二.选择语句Switch

2.1 普通的Switch

Go中的Switch语句形如C语言:

package main

import (  
    "fmt"
)

func main() {  
	finger := 8
    switch finger {
    case 1:
        fmt.Println("Thumb")
    case 2:
        fmt.Println("Index")
    case 3:
        fmt.Println("Middle")
    case 4:
        fmt.Println("Ring")
    case 5:
        fmt.Println("Pinky")
    default: //default case
        fmt.Println("incorrect finger number")
    }
}

因为Go语言的特性当然也可以写成switch finger := 8; finger {,

2.2 多条件的Switch

package main

import (  
    "fmt"
)

func main() {  
    letter := "i"
    switch letter {
    case "a", "e", "i", "o", "u":
        fmt.Println("vowel")
    default:
        fmt.Println("not a vowel")
    }
}

这段语句中,不管lettera、e、i、o、u中任意一个字母,都会输出vowel

2.3 无表达式的Switch

Switch的表达式可以默认,且默认的值是true,且case中可以放condition,若满足true的条件即可触发.

package main

import (  
    "fmt"
)

func main() {  
    num := 75
    switch {
	case num == 75:
		fmt.Println("num is 75")
    case num >= 0 && num <= 50:
        fmt.Println("num is greater than 0 and less than 50")
    case num >= 51 && num <= 100:
        fmt.Println("num is greater than 51 and less than 100")
    case num >= 101:
        fmt.Println("num is greater than 100")
    }
}

但此时的num并不能触发num is greater than 51 and less than 100,而只是输出了num is 75

2.3 fallthrough

使用fallthrough关键字可以让某个case执行完后,继续执行,例如:

package main

import (  
    "fmt"
)

func main() {  
    num := 75
    switch {
	case num == 75:
		fmt.Println("num is 75")
		fallthrough
    case num >= 0 && num <= 50:
        fmt.Println("num is greater than 0 and less than 50")
    case num >= 51 && num <= 100:
        fmt.Println("num is greater than 51 and less than 100")
    case num >= 101:
        fmt.Println("num is greater than 100")
    }
}
/* outputs
num is 75
num is greater than 0 and less than 50
*/

三.循环

Go语言的循环是C风格的,形如这样:

for initialisation; condition; post {  
}

刚好对标C语言的:

for (initialisation; condition; post)
{}

当然,go也支持breakcontinue:

package main

import (  
    "fmt"
)

func main() {  
    for i := 1; i <= 20; i++ {
        if i % 2 == 0 {
            continue
        } else if i > 10 {
			break
		} else {
			fmt.Print(i, " ")
		}
    }
}
/* outputs
1 3 5 7 9 
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康娜喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值