2.7 Functions and Control Flow
Functions in Rust are declared with fn. They accept parameters with explicit types and can optionally return a value declared after the ->.
2.7.1 Function Declaration
fn add(a: i32, b: i32) -> i32 { a + b } fn main() { let result = add(5, 3); println!("The sum is: {}", result); }
Key Points:
- No forward declarations are needed.
- The last expression in a function without a semicolon is the return value (or you can use
return <expr>;).
2.7.2 Comparison with C
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("The sum is: %d\n", result);
return 0;
}
2.7.3 Control Structures
Rust provides if, else if, and else for conditional code execution, as well as while, for, and loop for repetition. Unlike C, Rust’s for iterates over iterators (ranges, collections) rather than a classic integer index expression.
If Statements
fn main() { let x = 5; if x < 0 { println!("Less than zero"); } else if x < 10 { println!("A few"); } else { println!("Many"); } }
- Conditions must be of type
booland do not need parentheses. - Braces are mandatory for each code block.
(In C, non-zero integers are considered truthy, and parentheses around conditions are required.)
while Loop
fn main() { let mut x = 0; while x < 5 { println!("x is: {}", x); x += 1; } }
This is similar to C’s while loop but must use a bool condition. break or continue can be used for early exit or skipping to the next iteration.
for Loop
fn main() { for i in 0..10 { println!("{}", i); } let text = "Rust"; for ch in text.chars() { println!("{}", ch); } }
0..10creates a range from 0 to 9.- There is no C-style
for (int i = 0; …; i++)in Rust.
loop
loop creates an infinite loop, exited by break. It can optionally return a value:
fn main() { let mut count = 0; loop { println!("Count is: {}", count); count += 1; if count == 5 { break; } } }
Assignments in Conditions
Rust disallows assignments in if conditions:
fn main() {
let mut x = 5;
// if x = 10 { } // Error: expected `bool`, found `()`
}
In contrast, C allows if (x = 10) to assign 10 to x and then evaluate the expression’s truthiness.
match
Rust also provides the match construct for pattern matching—an advanced variant of C’s switch statement.