Functions and Control Flow
Learn to define functions, use `if`/`else`, `loop`, `while`, and `for` expressions to control program execution flow.
Functions and Control Flow is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What are Functions?
Functions are named blocks of code that perform a specific task. They are fundamental for organizing your code and making it reusable.
- Code Reusability: Write a piece of logic once and use it multiple times.
- Modularity: Break down complex problems into smaller, manageable parts.
- Readability: Give meaningful names to blocks of code, improving understanding.
Your First Rust Function
In Rust, you define a function using the fn keyword. The main function is the entry point of every Rust program.
Here's how to declare and call a simple function:
fn say_hello() {
println!("Hello from a function!");
}
fn main() {
say_hello(); // Call the function
println!("Back in main.");
}Functions with Parameters
Functions can accept input values called parameters. These allow your function to operate on different data each time it's called.
Parameters are defined with a name and a type, separated by a colon.
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Alice");
greet("Bob");
}Functions with Return Values
Functions can also return a value to the caller. You specify the return type after an arrow (->).
The last expression in the function body is implicitly returned. No semicolon needed for the return expression!
fn add_numbers(x: i32, y: i32) -> i32 {
x + y // No semicolon: this expression is returned
}
fn main() {
let sum = add_numbers(5, 7);
println!("The sum is: {}", sum);
}Making Decisions: `if`/`else`
The if expression allows your program to execute different code blocks based on a condition. Conditions must always be a bool (true/false).
- Use
iffor the first condition. - Use
else iffor additional conditions. - Use
elsefor a fallback if no other conditions are met.
Rust's if is an expression, meaning it can return a value!
If-Else Expressions in Action
Here's how you can use if and else to assign a value based on a condition. Notice how it behaves like a ternary operator from other languages.
fn main() {
let number = 7;
let message = if number < 10 {
"Small number"
} else {
"Large number"
};
println!("The number is: {}", message);
let other_num = 15;
if other_num % 2 == 0 {
println!("{} is even", other_num);
} else {
println!("{} is odd", other_num);
}
}Repeating Code: `loop`
The loop keyword creates an infinite loop. This is useful when you need to repeat an action until you explicitly decide to stop.
Use break to exit the loop. You can even return a value from a loop expression using break.
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Break and return a value
}
};
println!("The result is {}", result);
}Conditional Repetition: `while`
The while loop executes a block of code as long as a specified condition remains true. It's perfect for when you don't know exactly how many times you need to loop.
fn main() {
let mut count = 3;
while count != 0 {
println!("{}!", count);
count -= 1;
}
println!("LIFTOFF!!!");
}Iterating with `for` Loops
The for loop is used to iterate over a collection of items or a range of numbers. It's Rust's most common looping construct, making your code safe and concise.
- It's often used with ranges (e.g.,
1..4for 1, 2, 3 or1..=4for 1, 2, 3, 4). - It works with any type that implements the
Iteratortrait.
fn main() {
// Loop through a range
for number in 1..4 { // 1, 2, 3
println!("Number: {}", number);
}
// Loop through an array
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("The value is: {}", element);
}
}Control Flow Challenge
Consider the following Rust code. What will be the final value of result?
fn calculate_value(input: i32) -> i32 {
if input > 10 {
input * 2
} else if input == 5 {
input + 5
} else {
input
}
}
fn main() {
let result = calculate_value(5);
// What is result?
}Functions & Control Flow Recap
You've mastered the building blocks for dynamic programs!
- Functions: Organize and reuse code using
fn, parameters, and return values. if/else: Make decisions and conditionally execute code. Remember it's an expression!loop: Create infinite loops, exit withbreak, and return values.while: Loop as long as a condition is true.for: Iterate safely over collections and ranges.
These tools are essential for writing structured and efficient Rust programs!
Frequently asked questions
Is the “Functions and Control Flow” lesson free?
Yes — the full text of “Functions and Control Flow” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Functions and Control Flow”?
Learn to define functions, use `if`/`else`, `loop`, `while`, and `for` expressions to control program execution flow. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Functions and Control Flow” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Variables, Mutability, and Shadowing
- Primitive Data Types and Operators
- Functions and Control Flow