Go - 賦值運算子



下表列出了 Go 語言支援的所有賦值運算子:

運算子 描述 示例
= 簡單賦值運算子,將右側運算元的值賦給左側運算元 C = A + B 將 A + B 的值賦給 C
+= 加法賦值運算子,它將右側運算元新增到左側運算元,並將結果賦給左側運算元 C += A 等效於 C = C + A
-= 減法賦值運算子,它從左側運算元中減去右側運算元,並將結果賦給左側運算元 C -= A 等效於 C = C - A
*= 乘法賦值運算子,它將右側運算元乘以左側運算元,並將結果賦給左側運算元 C *= A 等效於 C = C * A
/= 除法賦值運算子,它將左側運算元除以右側運算元,並將結果賦給左側運算元 C /= A 等效於 C = C / A
%= 取模賦值運算子,它使用兩個運算元進行取模運算,並將結果賦給左側運算元 C %= A 等效於 C = C % A
<<= 左移賦值運算子 C <<= 2 等效於 C = C << 2
>>= 右移賦值運算子 C >>= 2 等效於 C = C >> 2
&= 按位與賦值運算子 C &= 2 等效於 C = C & 2
^= 按位異或賦值運算子 C ^= 2 等效於 C = C ^ 2
|= 按位或賦值運算子 C |= 2 等效於 C = C | 2

示例

嘗試以下示例以瞭解 Go 程式語言中可用的所有賦值運算子:

package main

import "fmt"

func main() {
   var a int = 21
   var c int

   c =  a
   fmt.Printf("Line 1 - =  Operator Example, Value of c = %d\n", c )

   c +=  a
   fmt.Printf("Line 2 - += Operator Example, Value of c = %d\n", c )

   c -=  a
   fmt.Printf("Line 3 - -= Operator Example, Value of c = %d\n", c )

   c *=  a
   fmt.Printf("Line 4 - *= Operator Example, Value of c = %d\n", c )

   c /=  a
   fmt.Printf("Line 5 - /= Operator Example, Value of c = %d\n", c )

   c  = 200; 

   c <<=  2
   fmt.Printf("Line 6 - <<= Operator Example, Value of c = %d\n", c )

   c >>=  2
   fmt.Printf("Line 7 - >>= Operator Example, Value of c = %d\n", c )

   c &=  2
   fmt.Printf("Line 8 - &= Operator Example, Value of c = %d\n", c )

   c ^=  2
   fmt.Printf("Line 9 - ^= Operator Example, Value of c = %d\n", c )

   c |=  2
   fmt.Printf("Line 10 - |= Operator Example, Value of c = %d\n", c )
}

編譯並執行上述程式後,將產生以下結果:

Line 1 - =  Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - <<= Operator Example, Value of c = 800
Line 7 - >>= Operator Example, Value of c = 200
Line 8 - &= Operator Example, Value of c = 0
Line 9 - ^= Operator Example, Value of c = 2
Line 10 - |= Operator Example, Value of c = 2
go_operators.htm
廣告
© . All rights reserved.