This is a creation in Article, where the information may have evolved or changed.
The go language supports several flow control statements such as the following:
conditional statements, the corresponding keywords are if, else and else if;
Select the statement, the corresponding keyword is switch, case and select (will be described in the introduction of the channel);
loop statements, corresponding keywords for and range;
Jump statement, corresponding to the keyword goto
In a specific application scenario, the Go language also adds the following keywords to meet richer control needs: Break,
Continue and Fallthrough.
1.1 Article statements
关于条件语句,需要注意以下几点:a.条件语句不需要使用括号将条件包含起来 () ;b.无论语句体内有几条语句,花括号 {} 都是必须存在的;c.左花括号 { 必须与 if 或者 else 处于同一行;d.在if之后,条件语句之前可以添加变量初始化语句,使用 ; 间隔;e.在有返回值的函数中,不允许将“最终的” return 语句包含在 if...else... 结构中,否则会编译失败:"function ends without a return statement"
编译失败的案例如下:
funcint)int{ if x==0{ return 5 }else { return x }}//失败的原因在于,Go编译器无法找到终止该函数的return语句。
1.2 SELECT statement
在使用 switch 结构时,我们需要注意以下几点:a.左花括号 { 必须与 switch 处于同一行;b.条件表达式不限制为常量或者整数;c.单个 case 中,可以出现多个结果选项;d.与C,java等语言规则相反,Go语言不需要用 break 来明确退出一个 case ;e.只有在 case 中明确添加 fallthrough 关键字,才会继续执行紧跟的下一个 case ;f.可以不设定 switch 之后的条件表达式,在此种情况下,整个 switch 结构与多个if...else... 的逻辑作用等同。
根据传入条件的不同,选择语句会执行不同的语句。下面的例子根据传入的整型变量i的不同而打印不同的内容:
switch I {case 0 : FMT. Printf ( "0" ) case 1 : FMT. Printf ( "1" ) case 2 : fallthrough case 3 : FMT. Printf ( "3" ) case 4 , 5 , 6 : FMT. Printf ( "4, 5, 6" ) default : FMT. Printf ( "Default" )}
Operation Result:
i = 0 o'clock, output 0;
i = 1 o'clock, output 1;
i = 2 o'clock, output 3;
i = 3 o'clock, output 3;
i = 4 o'clock, output 4, 5, 6;
i = 5 o'clock, output 4, 5, 6;
i = 6 o'clock, output 4, 5, 6;
i = other arbitrary value, output default
比较有意思的是, switch 后面的表达式甚至不是必需的,比如下面的例子:
switch { case 0 <= Num && Num <= 3: fmt.Printf("0-3") case 4 <= Num && Num <= 6: fmt.Printf("4-6") case 7 <= Num && Num <= 9: fmt.Printf("7-9")}
1.3 Loop statements
与多数语言不同的是,Go语言中的循环语句只支持 for 关键字,而不支持while和do-while结构。
sum := 0for i :=0;i<10;i++{ sum +=i}
可以看到比较大的一个不同在于 for 后面的条件表达式不需要用圆括号 () 包含起来。Go语言还进一步考虑到无限循环的场景,让开发者不用写无聊的 for (;;) {} 和 do {} while(1); ,而直接简化为如下的写法:
sum := 0for{ sum++ if sum>100{ break }}
在条件表达式中也支持多重赋值,如下所示:
a := []int{1,2,3,4,5,6}for i,j := 0len(a)-1;i<j;i,j = i+1,j-1{ a[i],a[j] = a[j],a[i]}
使用循环语句时,需要注意的有以下几点。a.左花括号 { 必须与 for 处于同一行。b.Go语言中的 for 循环与C语言一样,都允许在循环条件中定义和初始化变量,唯一的区别是,Go语言不支持以逗号为间隔的多个赋值语句,必须使用平行赋值的方式来初始化多个变量。c.Go语言的 for 循环同样支持 continue 和 break 来控制循环.但是它提供了一个更高级的break ,可以选择中断哪一个循环,如下例:
for j := 0;j<5;j++{ for i :=0 ;i<10;i++{ if i>5 { break Tag } fmt.Println(i) }}Tag:
上面例子中的break tag是用来终止Tag标签处的外层循环的.
1.4 Jump Statements
goto 语句的语义非常简单,就是跳转到本函数内的某个标签,如:
func myfunc () {i: =< Span class= "Hljs-number" > 0 here:fmt. Println (i) i++ if i < ten {goto here}}