Rust Functions Tutorial | Parameters & Return Values for Beginners (2026)
Video: Rust Functions Tutorial | Parameters & Return Values for Beginners (2026) by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Functions Tutorial | Parameters & Return Values for Beginners
Functions in Rust are defined using the fn keyword and allow you to organize code by encapsulating reusable logic. This tutorial covers creating basic functions, passing parameters (including string slices), and returning values using Rust’s concise syntax.
Code
// Basic function without parameters
fn greet() {
println!("Hello from a function!");
}
// Function with a string slice parameter
fn greet(name: &str) {
println!("Hello, {}!", name);
}
// Function with parameters and a return value
fn add(a: i32, b: i32) -> i32 {
a + b // No semicolon means this expression is returned
}
fn main() {
greet(); // Calls the basic greet function
greet("Alice"); // Calls greet with a name parameter
greet("Bob"); // Another call with a different name
let sum = add(5, 3); // Calls add and stores the returned value
println!("5 + 3 = {}", sum);
}
Key Points
- Functions are declared with the
fnkeyword followed by the function name and parentheses. - Parameters require explicit type annotations, such as
name: &strfor string slices. - Return types are specified after an arrow
->before the function body. - The last expression in a function without a semicolon is implicitly returned.
- The
main()function serves as the entry point for Rust programs.