Expressions & Flow · 11 min · free with an account

Functions

Lesson preview · about 30%

A function signature is a contract the compiler enforces at every call site.

Core idea

The last expression without a semicolon is the return value.

Start with the idea

Parameter types and the return type are always written out, never inferred across a function boundary. The last expression is the return value when you leave the semicolon off, which is why an accidental semicolon turns a function into one that returns the unit type and produces a type error.

The area function declares its contract before its body: two u32 parameters go in and one u32 comes out. That boundary lets rustc check a call without reading every line of the implementation. Inside the body, width * height is the tail expression. Its value becomes the return value because there is no semicolon after it. Adding one would change that final statement to unit, and rustc would point out the mismatch with -> u32.

The shout function shows that a body can have several steps before its tail value. text is borrowed as &str, to_uppercase creates an owned String, and push modifies that owned buffer. The final out expression moves the completed String to the caller.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics