Saturday, June 22, 2024

Rust: Control Flow

Rust: Control Flow

Rust: Control Flow

Control flow in Rust allows you to dictate the flow of execution in your code. It includes if/else statements, loops, and match expressions.

If/Else Statements

An if/else statement in Rust looks like this:

if condition { // code to execute if condition is true } else { // code to execute if condition is false }

Example:

fn main() { let x = 5; if x < 10 { println!("x is less than 10"); } else { println!("x is greater than or equal to 10"); } }

Output:

x is less than 10

Loops

Rust has three main types of loops: loop, while, and for. Here's an example of a for loop:

fn main() { for i in 1..5 { println!("{}", i); } }

Output:

1 2 3 4

Match Expressions

A match expression in Rust allows you to compare a value against a series of patterns and execute code based on the matching pattern. Here's an example:

fn main() { let x = 5; match x { 1 => println!("x is 1"), 2 => println!("x is 2"), _ => println!("x is not 1 or 2"), } }

Output:

x is not 1 or 2

Common Use Cases

Control flow is essential for writing logic in any programming language. In Rust, you can use control flow to handle different scenarios, iterate over collections, and make decisions based on conditions.

Importance in Interviews

Understanding control flow in Rust is crucial for technical interviews. Interviewers often ask questions that require you to demonstrate your knowledge of how to control the flow of execution in code.

Conclusion

Control flow in Rust is a fundamental concept that allows you to dictate the flow of execution in your code. By mastering if/else statements, loops, and match expressions, you can write more efficient and readable code.