Rust Tutorial

Rust - Operators Precedence



Rust Operators Precedence

Operator precedence (order of operations) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given expression.

For example, multiplication has higher precedence than addition. Thus, the expression 1 + 2 × 3 is interpreted to have the value 1 + (2 × 3) = 7, and not (1 + 2) × 3 = 9. When exponent is used in the expression, it has precedence over both addition and multiplication. Thus 3 + 52 = 28 and 3 × 52 = 75.

Operator Associativity

Operator associativity is the direction in which an expression is evaluated. For example:

let mut x = 10;
let mut y = 20;

//associativity of = operator is
//Left to Right, hence x will become 20
x = y;

As the associativity of = is left to right. Hence x is assigned the value of y.

Example:

The example below illustrates the operator precedence in Rust.

fn main() {
  //evaluates 5 * 2 first
  let retval1 = 15 - 5 * 2;

  //above expression is equivalent to
  let retval2 = 15 - (5 * 2);

  //forcing compiler to evaluate 15 - 5 first
  let retval3 = (15 - 5) * 2;

  println!("15 - 5 * 2 = {}", retval1);
  println!("15 - (5 * 2) = {}", retval2);
  println!("(15 - 5) * 2 = {}", retval3);
}

The output of the above code will be:

15 - 5 * 2 = 5
15 - (5 * 2) = 5
(15 - 5) * 2 = 20

Rust Operators Precedence Table

The following table lists the precedence and associativity of Rust operators. Operators are listed top to bottom, in descending precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. When operators have the same precedence, associativity of the operators determines the order in which the operations are performed.

PrecedenceOperatorDescriptionAssociativity
19PathsNA
18Method calls
17Field expressionsLeft to Right
16Function calls, Array indexingNA
15?Question mark operator
14-aUnary minus
!Bitwise or Logical NOT
*Dereference operator
&Shared borrow operator
&mutMutable borrow operator
13asType casting keywordLeft to Right
:: operator (multiple uses)
12*  /  %Multiplication, Division, Remainder
11+  -Addition, Subtraction
10<<  >>Bitwise left shift and right shift
9&Bitwise or Logical AND
8^Bitwise or Logical XOR
7|Bitwise or Logical OR
6==  !=Equality and InequalityRequire parentheses
<  <=  >  >=Less than, Less than or equal, Greater than, and Greater than or equal
5&&Logical ANDLeft to Right
4||Logical OR
3..  ..=Range literal, Assignment by range literalRequire parentheses
2=Direct assignmentRight to Left
+=  -=  *=  /=  %=Compound assignment by sum, difference, product, quotient and remainder
<<=  >>=Compound assignment by Bitwise left shift and right shift
&=  ^=  |=Compound assignment by Bitwise AND, XOR and OR
1returnreturn statementNA
breakbreak statement
closures

❮ Rust - Operators