WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Rust Β· Basic Β· question 6 of 100

What are the different types of control structures in Rust? Give examples of each.?

πŸ“• Buy this interview preparation book: 100 Rust questions & answers β€” PDF + EPUB for $5

In Rust, there are three types of control structures: 1. Conditional statements: Conditional statements are used to execute a block of code only when a certain condition is true. Rust has two types of conditional statements: if-else and match.

The if-else statement allows the execution of one of two blocks of code based on a condition. For example:

    let x = 5;
    if x > 0 {
        println!("x is positive");
    } else {
        println!("x is non-positive");
    }

The match statement is used to match a value with different patterns and execute the corresponding block of code. For example:

    let x = 5;
    match x {
        1 => println!("one"),
        2 | 3 => println!("two or three"),
        4..=10 => println!("four to ten"),
        _ => println!("something else"),
    }

2. Looping statements: Looping statements are used to execute a block of code repeatedly until a certain condition is met. Rust has two types of looping statements: loop and while.

The loop statement executes a block of code repeatedly until it is interrupted by a break statement. For example:

    let mut x = 0;
    loop {
        if x == 5 {
            break;
        }
        x += 1;
    }
    println!("x is {}", x);

The while statement executes a block of code repeatedly while a certain condition is true. For example:

    let mut x = 0;
    while x < 5 {
        x += 1;
    }
    println!("x is {}", x);

3. Control Flow Statements: Control Flow Statements are used to change the order of execution of a block of code. Rust has two types of control flow statements: break and continue.

The break statement is used to terminate a loop prematurely. For example:

    let mut x = 0;
    while x < 10 {
        if x == 5 {
            break;
        }
        x += 1;
    }
    println!("x is {}", x);

The continue statement is used to skip the current iteration of a loop and start the next one. For example:

    for x in 0..10 {
        if x % 2 == 0 {
            continue;
        }
        println!("{}", x);
    }

These control structures allow Rust developers to write more efficient and readable code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview β€” then scores it.
πŸ“ž Practice Rust β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Rust questions & answers β€” PDF + EPUB for $5

All 100 Rust questions Β· All topics