Greetings, coder! Today, we're delving into Rust to master arithmetic and logical operations. This foundation is fundamental for data manipulation and decision-making within the Rust environment.
Rust's primitive data types include i32
for whole numbers, f32
for decimal numbers, bool
for true/false values, and char
for single characters.
You can perform arithmetic operations — such as addition (+
), subtraction (-
), multiplication (*
), division (/
), and modulus (which represents the remainder of the division, %
) — on numerical types. Here's an example:
Rust1let a: i32 = 10; 2let b: i32 = 2; 3println!("{}", a + b); // Outputs: 12 4println!("{}", a - b); // Outputs: 8 5println!("{}", a * b); // Outputs: 20 6println!("{}", a / b); // Outputs: 5 7println!("{}", a % b); // Outputs: 0
In many programming languages, including Rust, there's a set of augmented assignment operators which are used as a shorthand method for modifying the value of our variables. These operators are +=
, -=
, *=
, \=
, and %=
. The +=
operator adds the value on its right to the variable on its left and assigns the result to the variable. The other operators work similarly. Let's take a look.
Rust1let mut number: i32 = 10; 2 3number += 2; // same as number = number + 2; 4println!("{}", number); // Outputs: 12 5 6number -= 4; // same as number = number - 4; 7println!("{}", number); // Outputs: 8 8 9number *= 3; // same as number = number * 3; 10println!("{}", number); // Outputs: 24 11 12number /= 12; // same as number = number / 12; 13println!("{}", number); // Outputs: 2 14 15number %= 2 // same as number = number % 2; 16println!("{}", number); // Outputs: 0
Logical operators — &&
(AND), ||
(OR), !
(NOT) — evaluate to bool
values — true
or false
within the Rust environment.
&&
outputs true
only if both boolean values are true
, whereas ||
returns true
if either value is true
. !
inverses the boolean value.
Below is an example of their application to two bool
values:
Rust1println!("{}", true && true); // true 2println!("{}", true && false); // false 3println!("{}", false && true); // false 4println!("{}", false && false); // false 5 6println!("{}", true || true); // true 7println!("{}", true || false); // true 8println!("{}", false || true); // true 9println!("{}", false || false); // false 10 11println!("{}", !true); // false 12println!("{}", !false); // true
Rust's logical operations are most commonly applied to variables. Here's a brief example:
Rust1let speed: i32 = 60; 2let min_speed: i32 = 30; 3let max_speed: i32 = 70; 4// Check if the speed is within the expected range. 5println!("{}", speed > min_speed && speed < max_speed); // Prints: true
Fantastic work! Today, we've learned about Rust's arithmetic operations and used logical operators to make complex decisions. Practice exercises are coming up to help solidify these critical concepts in Rust. Let the coding begin!