The Analogy: The Kitchen Pass
In a professional kitchen there is a shelf between the line and the dining room called the pass. The cook works on the bench, and when a dish is finished it goes on the pass. Whatever is sitting on the pass is what the waiter carries out. Not the pan it was cooked in, not the notes the cook made along the way -- just the one plate left in that one place. If the cook finishes the dish and then slides it into the fridge instead, the pass is empty, and the waiter carries out nothing at all.
Clipped above the bench is the order ticket. The ticket names every ingredient and its quantity, and it names the dish that comes back. It is not a suggestion; it is the contract between the dining room and the kitchen. The waiter does not need to know how the cook works, and the cook does not need to know who ordered it. Both of them only need the ticket to be complete and accurate.
A Rust function is exactly this arrangement. The signature is the ticket: fn area(w: u32, h: u32) -> u32 says two u32 values come in and one u32 goes back, and Rust will not let you leave either half blank the way a dynamic language would. The body is the bench, and the tail expression -- the last expression, with no semicolon -- is the pass. width * height on the last line is the dish going out. Write width * height; with a semicolon and you have put it in the fridge: the body now ends in a statement, the pass is empty, and the function returns ().
This is why error[E0308]: mismatched types ... expected u32, found ()` is the single most common error a newcomer hits, and why the fix is almost always deleting one character. It is also why so much Rust code has no return keyword in it. return is for walking out of the kitchen early; the normal path is to leave the answer on the pass. Once you see blocks, if, and match` as things that produce values rather than things that do steps, most of the language's shape follows from that one idea.
Syntax or Core Structure
A function declaration is fn, a name, a parenthesised parameter list where every parameter is annotated, an optional -> Type, and a block. Functions are items, so they may be declared in any order and used before they appear.
fn main() {
println!("area = {}", area(3, 4));
println!("label = {}", classify(42));
greet("Ada");
// A block is an expression: it evaluates to its tail.
let doubled = {
let base = 21;
base * 2
};
println!("doubled = {doubled}");
// `if` is an expression, so it can feed a `let` directly.
let sign = if doubled > 0 { "positive" } else { "non-positive" };
println!("sign = {sign}");
println!("first_even = {:?}", first_even(&[7, 9, 12, 15]));
println!("no_even = {:?}", first_even(&[7, 9, 15]));
}
// Items may appear in any order: `main` called `area` before this line.
fn area(width: u32, height: u32) -> u32 {
width * height // tail expression: no semicolon, no `return`
}
fn classify(n: i32) -> &'static str {
if n % 2 == 0 { "even" } else { "odd" }
}
// No `->` means the return type is `()`, the unit type.
fn greet(name: &str) {
println!("hello, {name}");
}
fn first_even(values: &[i32]) -> Option<i32> {
for &v in values {
if v % 2 == 0 {
return Some(v); // early exit is what `return` is for
}
}
None // tail expression
}
Output:
area = 12
label = even
hello, Ada
doubled = 42
sign = positive
first_even = Some(12)
no_even = None
Now add one semicolon and watch the contract break. This is area with the tail turned into a statement:
fn area(w: u32, h: u32) -> u32 {
w * h;
}
Output (trimmed):
error[E0308]: mismatched types
--> src/main.rs:1:28
|
1 | fn area(w: u32, h: u32) -> u32 {
| ---- ^^^ expected `u32`, found `()`
| |
| implicitly returns `()` as its body has no tail expression
2 | w * h;
| - help: remove this semicolon to return this value
The compiler names the cause in plain words -- "its body has no tail expression" -- and points at the exact character to delete. Learn to read this one, because it will greet you again every time you refactor a function and leave a stray semicolon behind.
Technical Depth: Statements, Expressions, and Signatures
What has a value and what does not
Rust divides code into statements, which do something and evaluate to nothing, and expressions, which evaluate to a value. Almost everything is an expression, which is why Rust needs so few dedicated constructs.
| Construct | Kind | Value it produces |
|---|---|---|
let x = 5; | statement | nothing -- let a = (let b = 5); does not compile |
5 | expression | 5 |
5; | statement | () -- the semicolon discards the value |
{ ...; tail } | expression | the tail expression, or () if the block ends in ; |
if c { a } else { b } | expression | a or b, and both branches must share one type |
match v { ... } | expression | the matching arm's value |
loop { ... break x; } | expression | the value handed to break |
while / for | expression | always (), so they cannot feed a let |
f(x) | expression | the function's return value |
Two consequences fall straight out of that table. An if without an else can only be (), because the missing branch has no value to offer -- so let x = if c { 1 }; is an error while let x = if c { 1 } else { 0 }; is fine. And loop is the only loop that can produce a value, which is exactly why retry logic in Rust tends to be written as let conn = loop { ... break c; };.
The signature is the inference boundary
Rust infers types inside a function body freely, and infers nothing across a function signature. That is a deliberate design choice with three payoffs: error messages stay local to one function instead of cascading across the crate, a change to a body can never silently change the public API, and compilation can be parallelised because each body can be checked against signatures alone. Closures are the deliberate opposite -- their parameter and return types are inferred from use -- and the Closures lesson picks that up.
| Position | Annotation |
|---|---|
fn parameter | required, always |
fn return type | required unless it is () |
let inside a body | optional when inference can reach it |
| closure parameter | optional, inferred from the call site |
const / static | required, always |
How parameters receive their arguments
A parameter is a pattern, not just a name, and the type decides whether the caller keeps its value.
fn copies(n: u32) {} // u32 is Copy: caller keeps its value
fn takes(s: String) {} // String is moved: caller loses it
fn borrows(s: &str) {} // borrowed: caller keeps it, no copy made
fn patterns((x, y): (f64, f64)) -> f64 { (x * x + y * y).sqrt() }
fn local_mut(mut n: u32) -> u32 { n += 1; n } // mut is local, invisible to the caller
mut in a parameter list is the detail people misread. fn local_mut(mut n: u32) does not let the function change the caller's variable; it declares that the function's own copy is mutable. Changing a caller's value requires &mut, which is the References and Borrowing lesson.
return, !, and the functions that never come back
return exists for early exit and nothing else. Idiomatic Rust reserves it for guard clauses and error paths, and leaves the ordinary answer as a tail expression. The ? operator is a specialised return for the error case, covered in the ? operator lesson.
A function annotated -> ! is diverging: it never returns normally. panic!, unreachable!, todo!, std::process::exit, and a bare loop {} all have type !, and ! coerces to every other type. That single rule is what makes panic! legal inside a match arm whose siblings all produce a u16:
const fn kib(n: usize) -> usize {
n * 1024
}
const BUFFER: usize = kib(4);
fn require_port(raw: &str) -> u16 {
match raw.parse::<u16>() {
Ok(p) if p >= 1024 => p,
Ok(p) => unreachable!("privileged port {p} slipped past validation"),
Err(_) => panic!("not a port: {raw}"),
}
}
fn main() {
let buf = [0u8; BUFFER];
println!("buffer = {} bytes", buf.len());
println!("port = {}", require_port("8080"));
}
Output:
buffer = 4096 bytes
port = 8080
kib is a const fn, which means it can run at compile time, which is why [0u8; BUFFER] is a legal array length. A const fn body is restricted -- no heap allocation, no trait methods that are not const -- but it is an ordinary function otherwise and can also be called at run time.
The other shapes a function takes
| Form | Where it lives | Called as |
|---|---|---|
fn name(..) -> T | module | name(..) |
const fn name(..) -> T | module | name(..), also in const contexts |
async fn name(..) -> T | module | name(..).await -- nothing runs until awaited |
fn name(&self, ..) | impl block | value.name(..) -- a method |
fn name(..) with no self | impl block | Type::name(..), like String::new() |
fn name<T: Trait>(..) | anywhere | monomorphised once per concrete T |
| a closure literal | an expression | captures its environment and infers its own types |
Real World Example: Grading a Batch of Submissions
Raw text arrives, some of it is junk, and an operator wants four numbers back. Written as one long main, that is a hundred lines nobody can test. Written as four functions with honest signatures, every piece is testable in isolation and the types document the pipeline: &str in, Option<u32> out, then &[&str] in, Summary out, then Summary in, String out.
#[derive(Debug)]
struct Summary {
counted: usize,
rejected: usize,
mean: f64,
best: u32,
}
/// None for anything that is not a plausible percentage.
fn parse_score(raw: &str) -> Option<u32> {
let n: u32 = raw.trim().parse().ok()?;
if n <= 100 { Some(n) } else { None }
}
fn letter_for(score: u32) -> char {
match score {
90..=100 => 'A',
80..=89 => 'B',
70..=79 => 'C',
60..=69 => 'D',
_ => 'F',
}
}
fn summarise(raw: &[&str]) -> Summary {
let mut counted = 0usize;
let mut rejected = 0usize;
let mut total = 0u32;
let mut best = 0u32;
for entry in raw {
match parse_score(entry) {
Some(score) => {
counted += 1;
total += score;
if score > best {
best = score;
}
}
None => rejected += 1,
}
}
// `if` as an expression, so `mean` needs no `mut` and no placeholder.
let mean = if counted == 0 {
0.0
} else {
f64::from(total) / counted as f64
};
Summary { counted, rejected, mean, best }
}
fn report(raw: &[&str]) -> String {
let s = summarise(raw);
let mean_letter = letter_for(s.mean.round() as u32);
let lines = [
format!("counted : {}", s.counted),
format!("rejected : {}", s.rejected),
format!("mean : {:.2} ({mean_letter})", s.mean),
format!("best : {} ({})", s.best, letter_for(s.best)),
];
lines.join("\n")
}
fn main() {
let submitted = ["88", " 94 ", "71", "oops", "105", "60", "79"];
println!("{}", report(&submitted));
}
Output:
counted : 5
rejected : 2
mean : 78.40 (C)
best : 94 (A)
Every signature in that file is a claim you can check without reading a body. parse_score returns Option<u32> and therefore cannot smuggle a 105 through -- the type says a value may be absent, and the if n <= 100 tail is the only thing that produces Some. letter_for takes a u32 and returns a char with no Option anywhere, so it is total: every input has an answer, and _ => 'F' is what makes that true. summarise takes a slice and touches no globals, so a test can hand it any array it likes. That is the practical value of the order ticket.
Notice what carries the control flow. parse_score uses .ok()? to turn a Result into an early return None, then leaves if n <= 100 { Some(n) } else { None } on the pass as its tail. letter_for is a single match expression with no return at all -- the arms are the value. summarise computes mean from an if expression rather than declaring let mut mean = 0.0; and overwriting it, which is the pattern from the Variables and Mutability lesson applied one level up.
The two numeric conversions in summarise are different on purpose. f64::from(total) works because every u32 is exactly representable in an f64, so the standard library offers a From implementation and no cast is needed. counted as f64 needs the cast because counted is a usize, and a 64-bit usize can hold values that f64 cannot represent exactly -- so there is deliberately no From<usize> for f64, and the language makes you write as to acknowledge it. The type system is telling you which conversion is free and which one you are choosing.
The one thing worth criticising here is Summary being returned by value with four public fields. That is fine at this size, and it is what you want while the shape is still moving. Once report is not the only consumer, the mean-to-letter step wants to live on the struct as a method, and the four format! lines want to be a Display implementation so that println!("{summary}") just works. Both of those are the Traits lesson; the point for now is that decomposition into plainly-typed functions is what makes that later refactor a small one.
Common Mistakes
- The stray semicolon on the tail expression.
w * h;makes the body end in a statement, so the function returns()and you geterror[E0308]: expectedu32, found()`. Delete the semicolon; do not addreturn`. - Adding
returnto the last line out of habit. It compiles, andclippy::needless_returnwill tell you it is noise. Reservereturnfor genuine early exits. - Omitting the return type and expecting inference.
fn double(n: i32) { n * 2 }does not infer-> i32; it declares a()function whose body is a type error. Signatures are never inferred. - Branches of an
ifexpression that disagree on type.if c { 1 } else { "one" }iserror[E0308]:ifandelsehave incompatible types. Both arms feed the same slot, so both must produce the same type. - Using an
ifwith noelseas a value.let x = if c { 1 };fails because the missing branch has nothing to offer. Supply theelse, or useOption. - Trying to get a value out of
fororwhile. They always evaluate to(). Useloopwithbreak value, or an iterator method likefindorsum. - Reading
mutin a parameter as a caller-visible effect.fn f(mut n: u32)mutates the function's own copy. To change the caller's value you need&mut u32. - Passing
Stringwhere&strwould do.fn f(s: String)forces the caller to give up ownership or clone. Take&strunless the function genuinely needs to keep the value. - Growing
maininstead of adding functions. A body that scrolls is a body that cannot be unit tested. Rust makes small functions free at run time --#[inline]is rarely needed, because the optimiser already sees across them within a crate.
Best Practices
- Return by tail expression and use
returnonly to leave early. It removes a keyword from every happy path and makes the guard clauses stand out. - Write the signature first and let it constrain the body. If you cannot name the parameter types and the return type, the function does not have one job yet.
- Take the least you need:
&stroverString,&[T]overVec<T>,&ToverT. The caller keeps its data and can pass more kinds of value. - Encode "might not have an answer" in the return type, not in a sentinel.
Option<u32>beats returning-1, andResult<T, E>beats returning a bool plus an out-parameter. - Prefer expression-shaped bodies. One
letbound to anifor amatchbeats alet mutfollowed by branches that assign into it. - Keep functions total where you can. A
matchwhose arms cover every case, likeletter_for, needs no error type and no documentation of what it rejects. - Mark compile-time-computable helpers
const fn. It costs nothing, and it lets the result be used for array lengths andconstitems later. - Use
#[must_use]on functions whose result is the entire point. A caller who ignores a computed value almost always has a bug, and the attribute turns that into a warning.
Practice Exercises
- Break it and read it. Write
fn perimeter(w: u32, h: u32) -> u32 { 2 * (w + h); }with the semicolon, compile it, and copy the full error into a comment. Then fix it three ways -- deleting the semicolon, addingreturn, and changing the return type to()-- and note which one the compiler suggested. - Make everything an expression. Rewrite this so it has no
mutand noreturn: a function that takes au32score and produces a&'static strof"fail","pass", or"distinction"usinglet mut label = "";and threeifstatements. Use a singlematchwith range patterns instead. - Find the diverging coercion. Write
fn parse_level(raw: &str) -> u8that accepts"low","mid","high"and callspanic!for anything else, all inside onematch. Explain in a comment why thepanic!arm typechecks alongside three arms that produce au8. - Decompose a monolith. Take a single
mainthat reads the array["12", "-3", "abc", "44"], keeps the values that parse as positivei32, and prints their count and sum. Split it intoparse_positive(&str) -> Option<i32>andtotals(&[&str]) -> (usize, i32), then add one#[test]for each that proves the junk entries are dropped.