Sub topic 1
Rust Functions and Control Flow
Prerequisites
You should know basic Rust syntax, how to run a Cargo program, primitive types such as integers and strings, and variables declared with let and let mut.
Defining and calling functions
A function is a named block of reusable code. Define it with fn, give it a name, list its parameters, and declare its return type after ->.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(2, 3);
println!("{sum}");
}add receives two i32 values and returns an i32. Rust infers that a + b is the return value because it is the final expression and has no semicolon. main calls the function and stores its result.
Statements versus expressions
A statement performs an action but does not produce a value. A let declaration is a statement:
let answer = 42;An expression produces a value. Function calls, arithmetic, and blocks are expressions. A semicolon changes an expression into a statement. Therefore, these blocks differ:
fn with_value() -> i32 {
42
}
fn without_value() {
42;
}The first function returns 42. The second evaluates 42 and discards it.
Parameters and return values
Parameters are typed inputs. The caller must pass values of the declared types. Rust functions can also borrow data through references, allowing the caller to keep ownership:
fn total(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
fn main() {
let numbers = vec![1, 2, 3];
println!("{}", total(&numbers));
println!("{numbers:?}");
}&numbers passes a shared reference. The function reads the vector without moving it.
Branching with if/else
if is an expression in Rust. Each branch must produce compatible types:
fn classify(n: i32) -> &'static str {
if n < 0 {
"negative"
} else if n == 0 {
"zero"
} else {
"positive"
}
}The condition must be a bool; Rust does not convert integers to booleans. The whole if expression can be assigned or returned.
Exercise
What does add(4, 6) return when add returns its final expression a + b?
Show answer
It returns 10.