βš™οΈ
World 3 Β· Building Blocks

Functions: Little Machines

Imagine a little machine. You drop something in one end, gears turn, and something useful pops out the other end. A juicer takes oranges and gives you juice! In Rust, those handy machines are called functions. βš™οΈ

Building a machine with fn

You make a function with the word fn (short for function), then a name, then a job to do inside the curly braces {}. You’ve already seen one: main is the function where every Rust program starts.

fn say_hi() {
    println!("Hi there!");
}
New word A function is a little machine that does a job. You can run it again and again just by saying its name.

Inputs and outputs

Real machines take stuff in and give stuff back. Functions do too!

  • The things you put in are called parameters (the inputs).
  • The thing that comes out is the return value (the output). The arrow -> shows what type comes out.

Here’s a machine that adds two numbers and gives back the answer:

We fed 3 and 4 into the add machine, and 7 came out! We stored it in a box called total and printed it. πŸŽ‰

Watch out! The last line of add is just a + b with no semicolon. In Rust, the last line without a semicolon becomes the value that comes out. Adding a ; there would jam the machine!
Think of it like this… A function is a vending machine. The buttons you press are the parameters, and the snack that drops down is the return value. 🍫
Try this! Make a new machine fn double(n: i32) -> i32 { n * 2 } and call it from main with double(5). Print the answer. Press β–Ά Run!

Quick quiz

In fn add(a: i32, b: i32) -> i32, what does the -> i32 mean?

Correct! The -> arrow shows the type of value the function returns. βš™οΈ

You learned… A function is a little machine made with fn. It takes parameters (inputs) and can give back a return value (output), and the last line with no semicolon is what comes out. Next up: leaving helpful notes in your code! πŸ“