2.7 Functions and Control Flow
Functions in Rust are declared with fn
, accept parameters with explicit types, and optionally return a value declared after ->
.
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 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
, else
for conditional code execution and while
, for
, and loop
for repetitions. Unlike C, Rust's for
iterates over iterators (ranges, collections) rather than an 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
bool
and require no parentheses. - Enclosing braces are mandatory for each code block.
C allows non-zero integers as truthy values, and parentheses around conditions are required.
while
Loop
fn main() { let mut x = 0; while x < 5 { println!("x is: {}", x); x += 1; } }
Similar to C's while
, but must use a bool
condition. break
or continue
can be used for early exit or to start 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..10
creates 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
, and 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 `()`
}
Compare this to C, where if (x = 10)
assigns 10 to x
and then checks the non-zero value.
match
Additionally, Rust has the match
construct for pattern matching—a much more powerful variant of C's switch statement.