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
= 按位包含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

上一篇: Go語言運算符 下一篇: Go語言條件和決策