💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## **1.if条件判断** Go语言中`if`条件判断格式如下: ``` if 表达式1 { 分支1 } else if 表达式2 { 分支2 } else{ 分支3 } ``` ## **2.for循环** for循环的格式如下: ``` for 初始语句;条件表达式;结束语句{ 循环体语句 } ``` ### **2.1.无限循环** ``` for { 循环体语句 } ``` for循环可以通过`break`、`goto`、`return`、`panic`语句强制退出循环。 ## **3.for range循环** Go语言中可以使用`for range`遍历数组、切片、字符串、map及channel。 通过`for range`遍历的返回值有以下规律: 1. 数组、切片、字符串返回索引和值。 2. map返回键和值。 3. 通道(channel)只返回通道内的值 ## **4.switch case** `switch`可以方便地对大量的值进行条件判断。 ``` func switchDemo1() { day := 3 switch day { case 1: fmt.Println("星期一") case 2: fmt.Println("星期二") case 3: fmt.Println("星期三") case 4: fmt.Println("星期四") case 5: fmt.Println("星期五") default: fmt.Println("无效的输入!") } } ``` Go语言规定每个`switch`只能有一个`defalut`分支。 一个分支可以有多个值。 ``` case 1, 3, 5, 7, 9: fmt.Println("奇数") ``` 分支可以使用表达式,这时switch后不需要跟判断的变量。 ``` func switchDemo4() { age := 30 switch { case age < 25: fmt.Println("好好学习吧") case age > 25 && age < 35: fmt.Println("好好工作吧") case age > 60: fmt.Println("好好享受吧") default: fmt.Println("活着真好") } } ``` `fallthrough`语法可以执行满足条件的case的下一个case。 ``` func switchDemo5() { s := "a" switch { case s == "a": fmt.Println("a") fallthrough case s == "b": fmt.Println("b") case s == "c": fmt.Println("c") default: fmt.Println("...") } } // 输出: a b ``` ## **5.goto(跳转到指定标签)** `goto`语句可以在快速跳出循环。 ## **6.break(跳出循环)** `break`语句可以结束`for`、`switch`和`select`的代码块。 ## **7.continue(继续下次循环)** `continue`语句可以结束当前循环,开始下一次的循环迭代过程,仅限在`for`循环内使用。 ``` func continueDemo() { forloop1: for i := 0; i < 5; i++ { // forloop2: for j := 0; j < 5; j++ { if i == 2 && j == 2 { continue forloop1 } fmt.Printf("%v-%v\n", i, j) } } } ```