位置:首頁 > 高級語言 > Go語言教學 > Go語言賦值運算符

Go語言賦值運算符

Go語言支持以下賦值運算符:

運算符 描述 示例
= 簡單的賦值操作符,分配值從右邊的操作數左側的操作數 C = A + B 將分配A + B的值到C
+= 相加並賦值運算符,它增加了右操作數左操作數和分配結果左操作數 C += A 相當於 C = C + A
-= 減和賦值運算符,它減去右操作數從左側的操作數和分配結果左操作數 C -= A 相當於 C = C - A
*= 乘法和賦值運算符,它乘以右邊的操作數與左操作數和分配結果左操作數 C *= A is equivalent to 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