Numeric Operators

Numeric operators generally follow C styles.

Unary Operators

OperatorDescription
+positive
-negative

#![allow(unused)]
fn main() {
let number = -5;

number = -5 - +5;
}

Binary Operators

OperatorDescriptionIntegerFloating-pointDecimal
+, +=plusyesyes, also with INTyes, also with INT
- -=minusyesyes, also with INTyes, also with INT
*, *=multiplyyesyes, also with INTyes, also with INT
/, /=divide (integer division if acting on integer types)yesyes, also with INTyes, also with INT
%, %=modulo (remainder)yesyes, also with INTyes, also with INT
**, **=power/exponentiationyesyes, also FLOAT**INTno
&, &=bit-wise Andyesnono
|, |=bit-wise Oryesnono
^bit-wise Xoryesnono
<<, <<=left bit-shiftyesnono
>>, >>=right bit-shiftyesnono
==equals toyesyes, also with INTyes, also with INT
!=not equals toyesyes, also with INTyes, also with INT
>greater thanyesyes, also with INTyes, also with INT
>=greater than or equals toyesyes, also with INTyes, also with INT
<less thanyesyes, also with INTyes, also with INT
<=less than or equals toyesyes, also with INTyes, also with INT

Note: when one of the operands to a binary operator is floating-point, it works with INT for the other operand and the result is floating-point.


#![allow(unused)]
fn main() {
let x = (1 + 2) * (6 - 4) / 2;  // arithmetic, with parentheses

let reminder = 42 % 10;         // modulo

let power = 42 ** 2;            // power

let left_shifted = 42 << 3;     // left shift

let right_shifted = 42 >> 3;    // right shift

let bit_op = 42 | 99;           // bit masking
}

Unary Before Binary

In Rhai, unary operators take precedence over binary operators. This is especially important to remember when handling operators such as ** which in some languages bind tighter than the unary - operator.


#![allow(unused)]
fn main() {
-2 + 2 == 0;

-2 - 2 == -4;

-2 * 2 == -4;

-2 / 2 == -1;

-2 % 2 == 0;

-2 ** 2 = 4;    // in some languages this means -(2 ** 2) == -4
}