In the Go language, there are many kinds of operators. The calculation order of these operators is determined according to certain rules. This is the so-called operator priority, which can determine the order of program execution. This article will introduce operator precedence in Go language.
1. Basic operators
Arithmetic operators include addition ( ), subtraction (-), multiplication (*), There are five types of division (/) and remainder (%), among which the priority from high to low is:
For example:
a := 10 202 // Multiplication first, then addition, which is equivalent to a := 10 (202) = 50
b := (10 20) 2 // Use Parentheses, add first, then multiply, equivalent to b := (10 20) 2 = 60
Relational operators include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=) and less than or equal to (<=), among which the priority is from high to low For:
For example:
a := 10 > 5 && 5 < 3 || 4 > 2 // Execute && first, then ||, which is equivalent to a := (10 > 5 && 5 < 3) || (4 > 2) = true
Logical operators include negation (!), AND (&&) and OR (||), the priorities from high to low are:
For example :
a := true || false && !true // First execute !, then &&, and finally ||, which is equivalent to a := true || false = true
2. Bitwise operators
Bitwise operators include bitwise AND (&), bitwise OR (|), XOR (^), left shift (<<) and right shift (>> ;) Five types, the priorities from high to low are:
For example :
a := 1 << 2 & 3 | 4 ^ 5 >> 2 // First execute <<, >>, then &, ^, and finally | , equivalent to a := 0 | 1 = 1
3. Assignment operator
Assignment operators include equal (=), plus equal (=), minus equal (-=) , multiplication is equal to (*=), division is equal to (/=), remainder is equal to (%=), left shift is equal to (<<=), right shift is equal to (>>=), bitwise AND is equal to ( &=), bitwise OR equal (|=) and bitwise XOR equal (^=), the priorities from low to high are:
For example:
a, b := 1, 2
a = b 3 4 // Perform multiplication first, then addition, and finally =, which is equivalent to a = a (b 3 4) = 15
By understanding the precedence of various operators in the Go language, we can write programs more accurately and better understand the calculation process of the program.
The above is the detailed content of What are the operator priorities in Go language?. For more information, please follow other related articles on the PHP Chinese website!