Lesson 4 of 20
Functions
Functions in Rust
Functions are declared with fn, followed by the name, parameters, and an optional return type:
fn add(x: i32, y: i32) -> i32 {
x + y
}
Expressions vs Statements
Rust is an expression-based language. The last expression in a function body is implicitly returned — no return keyword needed:
fn double(x: i32) -> i32 {
x * 2 // no semicolon — this is the return value
}
Adding a semicolon turns an expression into a statement (which returns ()):
fn oops(x: i32) -> i32 {
x * 2; // ERROR: expected i32, found ()
}
Early Return
Use return to return early:
fn first_positive(v: &[i32]) -> Option<i32> {
for &x in v {
if x > 0 {
return Some(x); // early return
}
}
None // implicit return at the end
}
Recursion
Functions can call themselves:
fn factorial(n: u64) -> u64 {
if n <= 1 { 1 } else { n * factorial(n - 1) }
}
Your Task
Implement three functions:
max_of_three(a: i32, b: i32, c: i32) -> i32— returns the largest of three integers.factorial(n: u64) -> u64— returns n! (factorial). Note: 0! = 1.is_prime(n: u32) -> bool— returns true if n is a prime number.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.