【转】Go 语言教程(2)——表达式
生活随笔
收集整理的這篇文章主要介紹了
【转】Go 语言教程(2)——表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
保留關鍵字
語言設計簡練,只有 25 個保留關鍵字。
break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var運算符
全部運算符、分隔符、以及其他符號。
+ & += &= && == != ( ) - | -= |= || < <= [ ] * ^ *= ^= <- > >= { } / << /= <<= ++ = := , ; % >> %= >>= -- ! ... . : &^ &^=運算符結合率從左到右。
優先級 運算符 ------------+---------------------------------------------+---------------------------- high * / & << >> & &^+ - | ^== != < <= < >=<- && low ||簡單位運算
0110 & 1011 = 0010 AND 都為 1。 0110 | 1011 = 1111 OR ?少?個為 1。 0110 ^ 1011 = 1101 XOR 只能?個為 1。 0110 &^ 1011 = 0100 AND NOT 清除標志位 a := 0 a |= 1 << 2 // 0000100: 在 bit2 設置標志位 a |= 1 << 6 // 1000100: 在 bit6 設置標志位 a = a &^ (1 << 6) // 0000100: 清除 bit6 標志位 x := 1 ^x // 取反運算 -0010初始化
初始化復合對象,必須使用類型標簽,且左大括號必須在類型尾部。
var a = struct{x int}{100} var b = []int{1, 2, 3}If
- 可以省略條件表達式括號
- 支持初始化語句,可以定義代碼塊局部變量
- 代碼塊左大括號必須在條件表達式尾部
不支持三元操作符 a > b ? a : b
For
For 支持三種循環方式,Go 中沒有 while 關鍵字語法,可以用 For 模擬。
s := "abc"// 常見 For 循環 // 計算出長度 n,避免多次調用 len 函數 for i, n := 0, len(s); i < n; i++ { println(s[i]) } // 替代 while (n > 0) {} n := len(s) for n > 0 { println(s[n]) n-- } // 替代 while (true) {} for { println(s) }Range
類似迭代器操作,返回 (索引, 值)或(鍵, 值)
Range 會復制對象,應該使用引用類型 slice、map。
for 循環的 range 格式可以對 slice 或者 map 進行迭代循環。
遍歷 slice 時,返回當前的下標和該下標對應元素的一個拷貝。
s := []int{1, 2, 3, 4, 5} for i, v := range s { // 復制 struct slice { pointer, len, cap } if i == 0 { s = s[:3] // 對 slice 修改,不會影響 range s[2] = 100 // 對底層數據的修改 } println(i, v) } 輸出: 0 1 1 2 2 100 3 4 4 5Switch
分支表達式可以是任意類型,不限于常量??梢允÷?break,默認自動終止。
繼續下一分支,可以使用 fallthrough,但不再判斷條件。
x := []int{1, 2, 3} i := 2 switch i { case x[1]: println("1") fallthrough case 1, 3: println("2") default: println("3") } 輸出 1 2省略條件表達式,可以當 if...else if...else 使用。
switch {case x[1] > 0: // if println("1") case x[1] < 0: // else if println("2") default: // else println("3") } // 帶初始化語句 switch i := x[2]; { case x[1] > 0: // if println("1") case x[1] < 0: // else if println("2") default: // else println("3") }Goto、Break、Continue
?持在函數內 goto 跳轉。標簽名區分??寫,未使?標簽引發錯誤。
func main() {var i intfor {println(i)i++if i > 2 { goto BREAK } } BREAK: println("break") EXIT: // Error: label EXIT defined and not used }配合標簽,break 和 continue 可在多級嵌套循環中跳出。
func main() { L1:for x := 0; x < 3; x++ { L2:for y := 0; y < 5; y++ {if y > 2 { continue L2 } if x > 1 { break L1 } print(x, ":", y, " ") } println() } } 輸出 0:0 0:1 0:2 1:0 1:1 1:2break 可?于 for、switch、select,? continue 僅能?于 for 循環。
作者:流年1004
鏈接:https://www.jianshu.com/p/21b90af6ea8f
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權并注明出處。
轉載于:https://www.cnblogs.com/jhhe66/articles/9506731.html
總結
以上是生活随笔為你收集整理的【转】Go 语言教程(2)——表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP安装memcache扩展
- 下一篇: BZOJ3709: [PA2014]Bo