Getting Started With Rust

lil_firelord
96.2K views

Open Source Your Knowledge, Become a Contributor

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

Create Content

Control Flow in Rust

If/Else

If/Else conditional statements behave very similar to other languages:

let x = 3;

if x < 10 {
	println!("{} is less than 10", x);
} else {
	println!("{} is greater than or equal to 10", x);
}

The boolean conditions do not need to be surrounded by parentheses, however each block following an "if" or "else" statment must be surrounded by curly braces.

As with many other languages you can also chain conditions together with "else if" as follows:

let x = 3;

if x < 0 {
	println!("{} is negative", x);
} else if x > 0 {
	println!("{} is positive", x);
} else {
	println!("{} is zero", x);
}

Loop

loop creates an infinite loop that can be controlled with continue, which will skip the current iteration, and break which will break the loop.

If we wanted to print all the multiples of three under 100 we could do something like this:

let mut x = 0;

loop{
	x++;

	if x >= 100 {
		println!("{} is now over 100 so we break the loop", x);
		break;
	}
	
	if x % 3 != 0 {
		continue; // The print statment following this if statement will not be printed
	}

	println!("{} is divisible by 3", x);
}

Note, this could be simplified by instead checking to make sure that the remainder is 0 and then print the statement accordingly, however I wanted to show how the continue statement worked.

While

while behaves very similarly to many other programming languages. As long as the boolean condition following while is true, the block will run.

If we were to convert our above loop into a while statement it would look like:

let mut x = 0;

while x <= 100 {
	x += 1;

	if x % 3 == 0 {
		println!("{} is divisible by 3", x);
	}
}

For-In Loop

Rust's for loop differs from C-style for loops.

for var in expression {
    code
}

The expression in this case is an Iterator and handles, you guessed it, iterating through collections of elements.

If we were to again rewrite the above loops into a For-In Loop it would look like :

for x in 1..101 {
	if x % 3 == 0 {
		println!("{} is divisible by 3", x);
	}
}

Where 1..101 is a Range where the lower element is inclusive and the upper element is exclusive.

Feel free to mess around with the code below

Playground

Loops

On To Functions

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