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