Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ EXPRESS THE WORK
BUILD NOTE 05 / 53

Give each idea a boundary.

Write functions with explicit inputs and useful return values.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Function signatures describe the contract between caller and callee. Parameter types and non-unit return types are written explicitly. Most Rust blocks are expressions: their final expression becomes the value if it has no trailing semicolon. Statements perform actions; a semicolon can turn a value-producing expression into a statement. Keep a function focused enough to test with ordinary values. Prefer returning a result to printing inside low-level logic, so callers can decide how to display it.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/functions/src/main.rs
fn total(price: u32, quantity: u32) -> u32 {
    price * quantity
}
fn main() {
    let invoice = {
        let shipping = 5;
        total(12, 3) + shipping
    };
    println!("total={invoice}");
}
↳ EXPECTED OUTPUT
total=41
  1. 1

    total returns its final multiplication expression.

  2. 2

    The inner block computes a value using a local shipping binding.

  3. 3

    The example uses small values; production arithmetic still needs bounds or checked operations.

From the extracted rust-workbench folder
cargo run -p lesson_functions

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write a function that computes the perimeter of a rectangle and test two sizes.

Reveal one possible solution +
solutions/functions/src/main.rs
fn perimeter(width: u32, height: u32) -> u32 {
    2 * (width + height)
}
fn main() {
    assert_eq!(perimeter(3, 5), 16);
    assert_eq!(perimeter(1, 1), 4);
}

05 Check your reasoning

QUICK SIGNAL CHECK

What returns a block’s final value?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.