Defining Functions
So far, all your code has lived inside fn main(). But what if you want to reuse a piece of code without copying and pasting it everywhere? That's where functions come in!
A function is like a mini-program inside your program. You give it a name, and then you can call it whenever you need it.
Your First Function
Here's how you define a simple function in Rust:
Let's break it down:
fnis the keyword that tells Rust "I'm making a function!"say_hellois the name we chose for the function()means the function doesn't need any extra information to do its job- The code inside
{}is what runs when you call the function
We call the function by writing its name followed by (). In the example above, we called it 3 times — that's 3 hellos without writing println! three times!
Functions with Parameters
What if you want your function to work with different values each time? You can give it parameters — these are like little slots where you pass in information:
The name: &str part says: "This function needs a text value, and we'll call it name inside the function." The &str type is Rust's way of saying "a piece of text that we're borrowing."
You can have multiple parameters too — just separate them with commas:
Each parameter needs its own type. Rust wants to know exactly what kind of data to expect!
Functions That Return Values
Some functions don't just do something — they give back a result. We use -> followed by the return type to say what kind of value the function returns:
Notice something interesting: we wrote a + b without a semicolon at the end. In Rust, the last expression in a function (without a semicolon) is automatically the return value. This is called an "implicit return."
You can also use the return keyword if you prefer to be explicit:
Both styles work, but most Rust programmers prefer leaving off the semicolon for the last expression.
Functions That Return bool
Functions can return any type, including booleans! This is great for checking conditions:
Summary
| Concept | Example |
|---|---|
| Define a function | fn greet() { ... } |
| Call a function | greet(); |
| Parameter | fn greet(name: &str) |
| Multiple parameters | fn add(a: i32, b: i32) |
| Return type | fn add(a: i32, b: i32) -> i32 |
| Implicit return | a + b (no semicolon) |
| Explicit return | return a + b; |
Now let's practice writing your own functions!