In the last one we wrote and ran our first rust program from scratch, today let's add some code to make much more...
Yes, rust like every other computer program controls the flow or processing of data by using special schemes. Ever heard about the if-else
, while
or for
statements? They are the basics of what most programming languages are trying to achieve, but rust has more!
Yeah, so that's valid rust, considering this
is a boolean(either true
or false
) value as well as that
and what
are variables with the same type as the function is supposed to return.
Let's do something simple(I am not gonna discuss rust data types for now ๐
). Your main.rs
file should look like this:
fn main() {
let x = 10; // This is how you initialise variables BTW
if x%2 == 0 {
println!("{} is always even", x);
else {
println!("{} is kinda odd", x);
}
}
That was simple if-else
, but similarly you can write if-else if
s as well:
if x < 10 {
println!("I am smol :3");
} else if x == 10 {
println!("Heh, average");
} else {
println!("THICC!!!");
}
NOTE: You did note that we didn't use paranthesis to enclose the boolean expression, that's just the convention you have to follow.
The syntax of this one will be kinda familiar to folks coming from Python! You are basically running over variables from a range/iterator and processing it one at a time.
let x = 10;
for i in x..20 { // read about the .. https://doc.rust-lang.org/1.1.0/book/for-loops.html
print!("{}", i); // Outputs :> 10111213141516171819
}
While lets you repeat until a conditional expression we_were_gone
is no longer true.
let mut x = 10; // This here, initialises a mutable variable that contains the value 10
while x != 0 {
println!("{} is not 0", x);
x -= 2;
}
Ok, a bit of an exaggeration huh! Rust allows you to write the same thing as a while true
with a single keyword, that's about it!
Let the code speak for itself:
let (x, y, z) = (10, 20, 30);
match (x < y, y < z) {
(true, true) => println!("This prints"),
(false, false) => println!("This just doesn't"),
_ => println!("Same here, but this is the default case...")
}
Quite self explanatory, right? That's how pattern matching works in rust! You can do a lot more, but that's all for now...