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
广告