栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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")
    }
}

这段语句中,不管letter是a、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")
    }
}

三.循环

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

for initialisation; condition; post {  
}

刚好对标C语言的:

for (initialisation; condition; post)
{}

当然,go也支持break、continue:

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, " ")
		}
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/712126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号