0
0
Rustprogramming~5 mins

For loop in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a for loop in Rust?
A for loop in Rust is a control flow statement that repeats a block of code for each item in a collection or range.
Click to reveal answer
beginner
How do you write a for loop to print numbers 1 to 5 in Rust?
You use a range with the syntax:
for i in 1..=5 {
    println!("{}", i);
}
This prints numbers from 1 to 5 inclusive.
Click to reveal answer
beginner
What does the range 1..5 mean in a Rust for loop?
The range 1..5 means numbers from 1 up to but not including 5, so it includes 1, 2, 3, and 4.
Click to reveal answer
intermediate
Can you use a for loop to iterate over elements in a vector in Rust?
Yes, you can loop over a vector like this: <pre>let v = vec![10, 20, 30];
for val in &v {
    println!("{}", val);
}</pre> This prints each element in the vector.
Click to reveal answer
beginner
What happens if you use for i in 0..=3 in Rust?
The loop runs with i = 0, 1, 2, 3 because ..= means inclusive range including the last number.
Click to reveal answer
What does the Rust for loop for i in 1..4 do?
ALoops with i = 1, 2, 3
BLoops with i = 1, 2, 3, 4
CLoops with i = 0, 1, 2, 3
DLoops with i = 4 only
How do you loop over all elements in a vector v in Rust?
Afor val in v { ... }
Bfor val in &v { ... }
Cfor val in v[] { ... }
Dfor val in v() { ... }
What symbol is used for an inclusive range in Rust?
A..=
B...
C..
D=>
Which of these is a valid for loop in Rust?
Afor i = 0 to 5 { println!("{}", i); }
Bfor (i=0; i<5; i++) { println!("{}", i); }
Cfor i in 0..5 { println!("{}", i); }
Dloop i in 0..5 { println!("{}", i); }
What will this code print?
for x in 3..=5 {
    println!("{}", x);
}
A5 only
B3 4
C4 5
D3 4 5
Explain how a for loop works in Rust and give an example using a range.
Think about how you count numbers one by one.
You got /4 concepts.
    Describe how to loop over elements in a vector in Rust and why borrowing is important.
    Remember Rust’s ownership rules.
    You got /4 concepts.