Go語言賦值運算子範例

2019-10-16 23:16:42

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
= 按位元包含OR和賦值運算子 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