Rust for Python Developers - Operators

Shin_O
61.3K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

This article was originally published on Medium

Follow me:

Arithmetic Operators

MeaningPythonRustRust Overloading Trait
Add two numbers++std::ops::Add
Subtract right operand from the left--std::ops::Sub
Multiply two numbers**std::ops::Mul
Divide left operand by the right one//std::ops::Div
Modulus/Remainder%%std::ops::Rem

Python and Rust share the same symbols as you see in the above table. Rust calls % as Remainder instead of the Modulus.

We will cover “Rust Overloading Trait” later in the Operator Overloading.

In Rust you can't use different data types in an operation. For example, if you try to subtract an unsigned integer from a singed integer, it will fail:

Rust uses the as keyword to cast between primitive types. Please read more about the cast in Rust here.

Exponent

Python uses ** symbol for exponents:

Rust uses pow, powi, and powf depends on the type:

In Rust, you can annotate a number type like 2u8 or 2_u8. u8 is an unsigned 8-bit integer type and i32 is a signed integer type.

i32 and f32 have a group of built-in methods. All the integer types u8, u16, u32, u64, u128, i16,i32, i64 , i128, isize, and usize have the pow method.

pub fn pow(self, exp: u32) -> i32

The above definition tells you that using the pow method raises self to the power of exp (which is u32) and returns i32 (a signed integer).

The floating-point types, f32 and f64 have powi and powf methods.

powi raises a number to an integer power and powf raises a number to a floating-point power.

pub fn powi(self, n: i32) -> f32
pub fn powf(self, n: f32) -> f32

Floor division

In Python we use // to find a floor division. For example 5//2=2.

Rust's floating-point types has the floor method.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content