多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
流程控制 1、if 基本语法 if condition { do something } ~~~ package main import( "fmt" ) func main() { num := 10 if num % 2 == 0 { fmt.Println("num is even") }else { fmt.Println("num is odd") } } ~~~ 2、if statement;condition { } ~~~ package main import( "fmt" ) func main() { if num := 10;num % 2 == 0 { fmt.Println("num is even") }else { fmt.Println("num is odd") } } ~~~ 3、for循环 break终止循环,跳出循环 continue 终止本次循环,继续下面的循环 4、无限循环 ~~~ func fort() { for { fmt.Printf("hello\n") time.Sleep(time.Second) } } ~~~ switch语句: 1、 ~~~ func switchtest() { finger := 4 switch finger{ case 1 : fmt.Println("first") case 2: fmt.Println("second") case 3: fmt.Println("third") case 4: fmt.Println("fourth") case 5: fmt.Println("fiveth") } } ~~~ fallthrough 匹配到值后自动执行下一个匹配项,然后退出循环。 default 默认当所有匹配项都匹配不上时的执行内容 ~~~ func switchtest() { finger := 10 switch finger{ case 1 : fmt.Println("first") fallthrough case 2: fmt.Println("second") case 3: fmt.Println("third") case 4: fmt.Println("fourth") case 5: fmt.Println("fiveth") default: fmt.Println("other is not in list") } } ~~~ 2、case语句中的判断: ~~~ func SwitchIfTest() { num := 75 switch { 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") } } ~~~ 练习:程序生成随机数字,用户输入,猜对了退出 ~~~ package main import( "fmt" "math/rand" ) func main() { //根据时间生成随机数的总和 rand.Seed(time.Now().UnixNano()) number := rand.Intn(100) fmt.Printf("请输入一个数字,数字的范围:[0-100]\n") for { var input int fmt.Scanf("%d\n",&input) var flag bool = false switch { case number > input: fmt.Printf("你输入的数字太小\n") case number == input: fmt.Printf("恭喜你,猜对了\n") flag = true case number < input: fmt.Printf("你输入的数字太大\n") } if flag { break } } } ~~~