Go运算符

463 阅读1分钟

运算符是告诉编译器执行特定的数学或逻辑的操作的符号。Go的内置符号包括

  • 算术运算符
  • 关系操作符
  • 逻辑运算符
  • 位运算符
  • 赋值操作符

以逻辑运算符为例,如下表

运算类型Go Operator
AND&&
OR
NOT

以位运算符为例,如下表

运算类型Go OperatorSample
AND&p & q
OR|p | q
XORp ^ q
NOT~~p
Left shift<<p << 1
Right shift>>p >> 2

赋值操作符 = += -= *= /= %= <<= >>= ^= |=

其他操作符

Go OperatorNote
&return the address of a variable
*pointer to a variable

运算符的优先级 operator precedence 优先级决定表达式的分组,影响表达式的求解。从高到底的顺序如下表

CategoryOperatorAssociativity
Postfix() [] -> . ++ - -Left to right
Unary+ - ! ~ ++ - - (type)* & sizeofRight to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >>Left to right
Relational< <= > >=Left to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XORLeft to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical ORLeft to right
Assignment= += -= *= /= %=>>= <<= &= ^==Right to left
Comma,Left to right