go學習筆記--條件和迴圈
阿新 • • 發佈:2021-01-05
Go學習筆記
條件和迴圈
for迴圈
- 與其他主要程式語言的差異,go僅支援迴圈關鍵字for
while 條件迴圈
while < 5
n := 0
for n < 5 {
n++
fmt.Println(n)
}
while 無限迴圈
while(true)
n := 0
for {
...
}
test code
package loop_test
import "testing"
func TestWhileLoop(t *testing.T){
n := 0
for n < 5 {
t.Log(n)
n++
}
}
if 條件
與其他主要程式語言的差異
- condition 表示式結果必須是布林值bool
- 支援變數賦值
if var declaration; condition {
// code to executed if the condition is true
}
package condition_test
import "testing"
func TestIfMultiSec(t *testing.T){
if a := 1 == 1; a{
t.Log("1==1")
}
}
func TestIfMultiSec1(t *testing.T){
if v,err := someFun(); err==nil{
t.Log("1==1")
}else{
t.Log("error")
}
}
switch 條件
與其他主要程式語言的差異
- 條件表示式不限制為常量或者整數;
- 單個 case 中,可以出現多個結果選項,使用逗號分隔; 與 C 語言等規則相反,Go 語言不需要用break 來明確推出一個
- 可以不設定 switch 之後的條件表示式,在次情況下,整個 switch 結構與多個 if…else…的邏輯作用等同
func TestSwitchMultiCase(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")
}
}
}
func TestSwitchMultiCondition(t *testing.T){
for i:=0;i<5;i++{
switch {
case i%2 == 0:
t.Log("Even")
case i%2 == 1:
t.Log("Odd")
default:
t.Log("it is not 0-3")
}
}
}