13

go 的程序控制

 4 years ago
source link: https://studygolang.com/articles/25998
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go 的程序控制大致分成三种 if for case 语句

1、 if 循环

if-else 语句之间可以有任意数量的 else if。

条件判断顺序是从上到下。如果 if 或 else if 条件判断的结果为真,则执行相应的代码块。 如果没有条件为真,则 else 代码块被执行。

语法结构

if condition{

}else if condition{

}else{

}

定义示列

package main
import "fmt"
func iftest()  {
    score :=61
    if score > 60{
        fmt.Println("成绩合格")
    } else if score >90{
        fmt.Println("成绩优秀")
    }else if score<0 {
        fmt.Println("成绩不能为负数")
    }else if score < 60 {
      fmt.Println("成绩不合格")
      } else{
        fmt.Println("成绩不合法")
    }
}

func main()  {
     iftest()
    // 输出  
    成绩合格
}

2、for 循环

go 循环只有一种叫做for

语法结构

for initialisation; condition; post {

}

初始化语句只执行一次。循环初始化后,将检查循环条件。如果条件的计算结果为 true ,则 {} 内的循环体将执行,

接着执行 post 语句。post 语句将在每次成功循环迭代后执行。在执行 post 语句后,条件将被再次检查。

如果为 true, 则循环将继续执行, 否则 for 循环将终止。

示列

package main
import "fmt"

func fortest1()  {
    for i :=1;i <=10;i++{
        fmt.Println(i)
    }
}

// 输出

1
2
3
4
5
6
7
8
9
10

//在 go 中 break语句在完成执行之前突然终止for 循环,之后程序将会在for 循环下开始下一行
 代码开始执行

 for i:=2; i<=20 ;i+=2{
        if i >8{
            break
        }
        fmt.Printf("%d",i)
    } 
    fmt.Printf("\nline after for loop")

// 输出 当 i的值大于8后, fmt.Printf("%d",i) ,就终止执行了,执行最后一个fmt.Print
2468
line after for loop

// continue
continue 语句用来跳出 for 循环中当前循环,
在 continue 语句后的所有的 for 循环语句都不会在本次循环中执行。循环体会在一下次循环中继续执行。

    for i :=1;i<=10;i++{
        if i%2 ==0{
            continue
        }
        fmt.Printf("%d",i)
    }
}

// 输出 ,当于为0 的不输出
13579  

func main()  {
    fortest1()

}

// go 的无限循环语句

for  {
        fmt.Println("Hello World")
        }

3、switch 语句

switch 语句用于基于不同条件执行不同动作,每个case 分之都是唯一的,从上至下逐以测试,直到匹配为止

switch 语句的执行过程从上至下,直到找到匹配项,匹配项后面也不需要加break

switch 默认情况下case 最后带break 语句,匹配成功后不会执行其他case,可以使用fallthrough

语法结构如下

switch var1 {

case val1:

...

case val2:

...

default:

...

}

package main
import "fmt"

func switchtest1()  {
    var scores int = 90
    switch scores{
    case 90:
        fmt.Println("very good score")
        fallthrough
    case 80:
        fmt.Println("good score")
    case 60:
        fmt.Println("just ok")
    }

}

输出 ,当在case 90 条件下新增 fallthrough 时,case 80 的条件也会输出
good score

very good score  

func main()  {

    switchtest1()
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK