0
0
Rustprogramming~5 mins

Loop construct in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax of an infinite loop in Rust?
In Rust, an infinite loop is created using the loop keyword followed by a block of code:<br>
loop {
    // code to repeat forever
}
Click to reveal answer
beginner
How do you exit a loop early in Rust?
You use the break keyword to exit a loop before it naturally ends.<br>Example:<br>
loop {
    if condition {
        break;
    }
}
Click to reveal answer
beginner
What is the difference between while and for loops in Rust?
while loops run as long as a condition is true.<br>for loops iterate over items in a collection or range.<br>Example:<br>
while x < 5 {
    x += 1;
}
for i in 0..5 {
    println!("{}", i);
}
Click to reveal answer
intermediate
How can a loop return a value in Rust?
A <code>loop</code> can return a value by using <code>break</code> with a value.<br>Example:<br><pre>let result = loop {
    if condition {
        break 42;
    }
};
println!("{}", result); // prints 42</pre>
Click to reveal answer
beginner
What is the purpose of the continue keyword in Rust loops?
continue skips the rest of the current loop iteration and moves to the next one.<br>Example:<br>
for i in 0..5 {
    if i == 2 {
        continue; // skip printing 2
    }
    println!("{}", i);
}
Click to reveal answer
Which keyword creates an infinite loop in Rust?
Awhile
Bfor
Cloop
Drepeat
How do you stop a loop immediately in Rust?
Abreak
Bexit
Cstop
Dreturn
What does the continue keyword do inside a loop?
AEnds the loop
BSkips to the next iteration
CRestarts the program
DPauses the loop
Which loop type is best to iterate over a range of numbers in Rust?
Ado-while
Bwhile
Cloop
Dfor
How can a loop return a value in Rust?
AUsing <code>break</code> with a value
BUsing <code>yield</code>
CUsing <code>continue</code> with a value
DUsing <code>return</code> inside the loop
Explain how to create and control loops in Rust, including how to exit or skip iterations.
Think about how you repeat tasks and stop or skip steps.
You got /4 concepts.
    Describe how a loop can return a value in Rust and give an example.
    Remember that break can send a value out of the loop.
    You got /3 concepts.