Go從入門到精通之條件與循環

  • 2019 年 10 月 6 日
  • 筆記

Go從入門到精通之條件與循環

0.導語

本節續學上節Go,先來談談算數運算符以及一起特殊運算符操作,最後學習本節的重點:條件循環。(學習來自極客時間Go課程)。

1.運算符

算數運算符

Go語言沒有前置的++,–

用==比較數組

在其他語言當中,用==比較是比較兩個數組的引用,而不是值,但是Go不一樣。

  • 相同維數且含有相同個數元素的數組才可以比較
  • 每個元素都相同的才相等

位運算符

&^按位零 ,如下:

1 & ^0 --- 1  1 & ^1 --- 0  0 &^ 1 --- 0  0 &^ 0 --- 0  

上述綜合例子:

package operator_test  import (      "testing"  )  func TestCompareArray(t *testing.T) {      a := [...]int{1, 2, 3, 4}      b := [...]int{1, 3, 4, 5}      // c := [...]int{1, 2, 3, 4, 5}      d := [...]int{1, 2, 3, 4}      t.Log(a == b) //false 長度,維數都相同,但元素不同      //數組長度不同,編譯錯誤!      // t.Log(a == c) //invalid operation: a == c (mismatched types [4]int and [5]int)      t.Log(a == d) //true 長度,維數相同,元素都相同  }  const (      Readable   = 1 << iota //1      Writable               //10      Executable             //100  )  func TestBitClear(t *testing.T) {      a := 7 //0111      a = a &^ Readable      a = a &^ Executable      t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable) //false true false  }  

2.循環

Go語言僅支援循環關鍵字for

c/c++中

for(j:=7;j<=9;j++)  

Go中 不需要前後括弧!

while條件循環

while(n<5)可表示為:

n:=0  for n<5 {      n++      fmt.Println(n)  }  

無限循環

while(true)可表示為:

n:=0  for {      ...  }  

if條件

不需要()

if condition {      ...  } else if {      ...  } else {      ...  }  

與其他主要程式語言的差異:

  • condition表達式結果必須為布爾值
  • 支援變數賦值(可以用來判斷函數返回值)
if var declaration; condition {      ...  }  if v,err := someFunc(); err==nil {      ...  } else {      ...  }  

switch 條件

不限制常量整數表達式

switch os := runtime.GOOS; os{  case "darwin":      ...  case "linux":      ...  default:      ...  

Go語言中默認是添加了break,可以不用添加!

上述綜合例子:

package condition_test  import (      "testing"  )  func TestIfMultiSec(t *testing.T) {      if a := 1 == 1; a {          t.Log("1==1")      }        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")          }      }      for i := 0; i < 5; i++ {          switch { //這裡沒有switch表達式!在此種情況下,整個switch結構與多個if...else...的邏輯作用等同          case i%2 == 0:              t.Log("Even")          case i%2 == 1:              t.Log("Odd")          default:              t.Log("unknow")          }      }  }  func TestWhileLoop(t *testing.T) {      n := 0      for n < 5 {          t.Log(n)          n++      }  }  

總結

(1)條件表達式不限制為常量或整數表達式

(2)單個case中,可以出現多個結果選項,使用逗分隔;

(3)與C語言等規則相反,Go語言不需要用break來明確退出一個case;

(4)可以不設定switch之後的條件表達式,在此種情況下,整個switch結構與多個if…else…的邏輯作用等同。