08丨条件和循环
08丨条件和循环
编写结构化程序
循环
与其他主要编程语言的差异
Go语言仅支持循环关键字for

代码示例

package ch5 import "testing" func TestWhileLoop(t *testing.T) { //while 的写法 m := 0 for m < 5 { t.Log("m:", m) m++ } //for的写法 for n := 0; n < 5; n++ { t.Log("n:", n) } }
if条件

与其他主要编程语⾔的差异
1. condition 表达式结果必须为布尔值
2. ⽀持变量赋值:
if var declaration; condition {
// code to be executed if condition is true
}
func TestIf(t *testing.T) { if a := 1 == 1; a { t.Log("1==1") } //if v, err := someFun(); err = nil{ // t.Log("1==1"), // } else { // t.Log("1==1") // } }
switch条件
与其他主要编程语言的差异
1.条件表达式不限制为常量或者整数
2.单个case中,可以出现多个结果选项,使用逗号分隔;
3.与C语言等规则相反,Go语言不需要用 break来明确退出一个case;
4.可以不设定 switch之后的条件表达式,在此种情况下,整个switch结构与多个if...else..的逻辑作用等同
func TestSitchCase(t *testing.T) { for i := 0; i < 5; i++ { switch i { case 0, 2: t.Log("Even") case 1, 3: t.Log("Odd") default: t.Log("it is not 0-3") } } } //默认不需要加 break func TestSitchConditionCase(t *testing.T) { for i := 0; i < 5; i++ { switch { // 可以代替if....else if.....else case i%2 == 0: t.Log("Even") case i%2 == 1: t.Log("Odd") default: t.Log("unkown") } } }
本文来自博客园,作者:元贞,转载请注明原文链接:https://www.cnblogs.com/yuleicoder/articles/14305673.html
浙公网安备 33010602011771号