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!");
}
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. π
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!
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. βοΈ
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! π