Complete the code to create an infinite loop using the correct Rust keyword.
fn main() {
[1] {
println!("Hello, world!");
break;
}
}The loop keyword creates an infinite loop in Rust. Here, it runs once and then breaks.
Complete the code to loop over numbers from 1 to 5 and print each number.
fn main() {
for i in [1] {
println!("{}", i);
}
}The range 1..=5 includes numbers from 1 to 5 inclusive.
Fix the error in the loop that should print numbers 0 to 4.
fn main() {
let mut count = 0;
while [1] {
println!("{}", count);
count += 1;
}
}The condition count < 5 ensures the loop runs while count is less than 5, printing 0 to 4.
Fill both blanks to create a loop that prints even numbers from 2 to 10.
fn main() {
for num in [1] {
if num [2] 2 == 0 {
println!("{}", num);
}
}
}The range 2..=10 includes numbers 2 to 10. The modulus operator % checks if a number is even.
Fill all three blanks to create a loop that collects squares of numbers greater than 3 from 1 to 5.
fn main() {
let squares: Vec<i32> = (1..=5)
.filter(|&[1]| [1] [2] 3)
.map(|[3]| [3] * [3])
.collect();
println!("{:?}", squares);
}The variable x is used in the closure. The filter keeps numbers greater than 3, and map squares them.