Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Operators

Arithmetic

OperatorMeaningExample
+additionx + y
-subtractionx - y
*multiplicationx * y
/divisionx / y
%modulox % y
**exponentiationx ** y

Comparison

OperatorMeaningExample
==equalx == y
!=not equalx != y
<less thanx < y
<=less than or equalx <= y
>greater thanx > y
>=greater than or equalx >= y

Logical

OperatorMeaningExample
andlogical AND (short-circuit)x and y
orlogical OR (short-circuit)x or y
notlogical NOTnot x

and and or are keywords, not symbols. They short-circuit: the right operand is only evaluated if needed.

Bitwise

OperatorMeaningExample
&bitwise ANDx & y
^bitwise XORx ^ y
~bitwise NOT~x
<<left shiftx << y
>>right shiftx >> y

Unary

OperatorMeaningExample
-negation-x
notlogical NOTnot x
~bitwise NOT~x

Precedence

From highest to lowest binding power:

PrecedenceOperatorsAssociativity
25. () ?left (postfix)
21- not ~ (unary)prefix
19**right
17* / %left
15+ -left
13<< >>left
11&left
9^left
7== != < <= > >=left
5andleft
3orleft
1= += -= *= /= %=right

Parentheses override precedence:

x + y * z       // y * z first
(x + y) * z     // x + y first
-a + b ** 2     // (-a) + (b ** 2)

Compound Assignment

OperatorDesugars to
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y

Works on fields too:

p.x += 10        // p = Point { x: p.x + 10, ..p }
lexer.pos += len

Try Operator

The postfix ? operator propagates errors from Result values:

fn read_config(path: String) -> Result<Config, Error>:
  let contents = read_file(path)?     // returns Err early if read fails
  let config = parse(contents)?
  Ok(config)

? desugars to a match on the Try trait — on Err, it returns the error; on Ok, it unwraps the value.

Chaining:

fn combine(x: Result<i64, String>, y: Result<i64, String>) -> Result<i64, String>:
  Ok(x? + y?)