capypad
0 day streak
rust / beginner
Snippet

Defining and Calling Functions in Rust

Functions are reusable blocks of code in Rust. They are defined using the `fn` keyword followed by the function name, parameters in parentheses, and an optional return type. Parameters need type annotations. The return type is specified after `->`. If a function returns a value, the last expression is implicitly returned. You can call functions by using their name followed by parentheses, passing arguments that match the parameter types.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
 
fn main() {
let message = greet("World");
println!("{}", message);
let result = add(15, 27);
println!("15 + 27 = {}", result);
}
 
fn add(a: i32, b: i32) -> i32 {
a + b
}
Breakdown
1
fn greet(name: &str) -> String {
Function definition with a string slice parameter and String return type
2
format!("Hello, {}!", name)
Macro that creates a formatted String with interpolation
3
}
Function body closing brace - implicit return of formatted string
4
fn main() {
Entry point function - Rust programs start here
5
let message = greet("World");
Calling greet with a string literal, storing result in message
6
println!("{}", message);
Macro to print the message to console
7
let result = add(15, 27);
Calling add function with two i32 values
8
fn add(a: i32, b: i32) -> i32 {
Function with two i32 parameters returning i32, no explicit return needed