Functions are one of the most important building blocks in Rust programs. They let you group code into reusable units that can be called multiple times.
In this tutorial, you’ll learn how to define a function in Rust, the rules for naming functions, and how to call a function
Defining a Function #
A function in Rust is defined using the fn keyword, followed by the function’s name, parameters (if any), and a body enclosed in curly braces {}.
Here’s a simple function:
fn greet() {
println!("Hello from Rust!");
}
Code language: Rust (rust)How it works:
fn→ tells Rust we’re defining a functiongreet→ the function’s name()→ empty parentheses (no parameters in this case){ ... }→ the function body, where the code runs
Function Naming Rules #
Rust uses snake_case for function names:
- all lowercase letters
- words separated by underscores
_
For example:
fn say_hello() {}
fn calculate_area() {}
Code language: Rust (rust)These are valid function but do not follow the naming rules:
fn SayHello() {} // looks like Java/C#
fn calculateArea() {} // camelCase, not idiomatic in Rust
Code language: Rust (rust)Calling a Function #
To run a function, just write its name followed by parentheses ().
fn greet() {
println!("Hello from Rust!");
}
fn main() {
greet(); // function call
greet(); // can be called multiple times
}
Code language: Rust (rust)Output:
Hello from Rust!
Hello from Rust!Code language: Rust (rust)Notice that main is a special function where every Rust program begins execution. From inside main, we call greet().
Functions with Parameters #
Functions can also accept parameters (inputs).
fn greet_person(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet_person("Alice");
greet_person("Bob");
}
Code language: Rust (rust)Here:
name: &str→ means the function expects a string slice parameter"Alice"and"Bob"→ values passed into the function
Output:
Hello, Alice!
Hello, Bob!Code language: Rust (rust)Returning Values #
A function can return a value using the -> symbol followed by the type.
fn main() {
let result = greet_person("Alice");
println!("{}", result);
}
fn greet_person(name: &str) -> String {
format!("Hello, {}!", name)
}
Code language: Rust (rust)How it works:
greet_persontakes a parameternameof type&str(a string slice, used for borrowed string data).- It returns a
String(an owned, growable string in Rust). format!is used to create a newStringwith the given name inside.- In
main, we callgreet_person("Alice")and store the result inresult. - Finally, we print the greeting.
Summary #
- Functions are defined with
fnand follow snake_case naming. - You call functions with
function_name(). - Functions can take parameters (inputs) and return values (outputs).
- Use
-> Typeto specify the return type. - The special
mainfunction is the entry point of every Rust program.