Skip to content

Latest commit

 

History

History
69 lines (59 loc) · 1.24 KB

1.md

File metadata and controls

69 lines (59 loc) · 1.24 KB

第05章 条件和循环

1.1 循环

与其他主要编程语言的差异

  • go语言仅支持循环关键字for
func TestWhileLoop(t *testing.T)  {
	n:=0
	for n < 5 {
		t.Log(n)
		n++
	}
}

1.2 if条件

与其他主要编程语言的差异

  • condition表达式结果必须为布尔值

  • 支持变量赋值

两段式写法,支持函数写法

func TestCondition(t *testing.T)  {
	if a :=1==1;a {
		t.Log(a,"1")
	}else {
		t.Log(a,"2")
	}
}

1.3 switch条件

与其他主要编程语言的差异

  • 条件表达式不限制为常量或者整数
  • 单个case中,可以出现多个结果选项,使用逗号分隔
  • 与c语言等规则相反,go语言不需要用break来确定退出一个case
  • 可以不设定switch之后的条件表达式,在此种情况下,整个switch结构与多个if else 的逻辑作用相同
func TestSwitch(t *testing.T)  {
	for i:=0;i<5 ;i++  {
		switch i {
		case 0,2:
			t.Log("111111")
		case 1,3:
			t.Log("222222")
		default:
			t.Log("000000")
		}
	}
}

func TestSwitch2(t *testing.T)  {
	for i:=0;i<5 ;i++  {
		switch {
		case i%2==0:
			t.Log("111111%")
		case i%2==1:
			t.Log("222222%")
		default:
			t.Log("000000")
		}
	}
}