Skip to content

Instantly share code, notes, and snippets.

@de-sh
Created March 18, 2020 12:09
Show Gist options
  • Save de-sh/697355c2c62c3463c4a9ab5c8c73b4d6 to your computer and use it in GitHub Desktop.
Save de-sh/697355c2c62c3463c4a9ab5c8c73b4d6 to your computer and use it in GitHub Desktop.
Introducing the basic control-flow syntax of Rust

Control Flow

In the last one we wrote and ran our first rust program from scratch, today let's add some code to make much more...

Control flow?

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!

if this { return that; } else { return what; } ?

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 ifs 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.

for

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 we_were_gone {} // stuff happened I guess...

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;
}

Let's loop { this }

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!

Some match making ๐Ÿ˜

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...

Please contribute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment