Loops as Expressions
Part of the Logic & Flow section of Coddy's Rust journey — lesson 5 of 66.
In most programming languages, loops are statements that execute code repeatedly. But Rust has a unique feature: loops can also be expressions that return a value. This means you can assign the result of a loop to a variable.
To return a value from a loop, you use break followed by the value you want to return:
let result = loop {
// some condition checking
if condition_met {
break 42; // exit loop and return 42
}
};Here's a practical example that finds the first even number starting from 10:
let mut counter = 10;
let first_even = loop {
if counter % 2 == 0 {
break counter; // return the even number
}
counter += 1;
};
println!("First even number: {}", first_even);The loop continues until it finds an even number, then uses break counter to exit the loop and return that number. The returned value gets assigned to first_even.
Challenge
EasyYou will receive a starting number as input. Read the input, convert it to an integer, and use a loop as an expression to find the first number divisible by 7 starting from that number.
Requirements:
- Use a
loopexpression that returns a value - Start checking from the input number
- Find the first number that is divisible by 7 (remainder is 0 when divided by 7)
- Use
breakto return the found number from the loop - Print the result
Input: A single integer representing the starting number
Output: Print the first number divisible by 7 starting from the input number
Cheat sheet
In Rust, loops can be expressions that return a value. Use break followed by a value to exit the loop and return that value:
let result = loop {
if condition_met {
break 42; // exit loop and return 42
}
};Example finding the first even number:
let mut counter = 10;
let first_even = loop {
if counter % 2 == 0 {
break counter; // return the even number
}
counter += 1;
};
println!("First even number: {}", first_even);Try it yourself
use std::io;
fn main() {
// Read input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let start_number: i32 = input.trim().parse().expect("Invalid input");
// TODO: Write your code below
// Use a loop expression to find the first number divisible by 7
// Print the result
// println!("{}", result);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together