capypad
0 day streak
rust / beginner
Snippet

Defining and Calling Functions

Functions in Rust are defined with 'fn'. Parameters need type annotations. The return type is specified after '->'. Rust automatically returns the last expression. Functions can return multiple values using tuples.

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 calculate(x: i32, y: i32) -> (i32, i32, i32) {
(x + y, x - y, x * y)
}
 
fn main() {
let message = greet("World");
println!("{}", message);
let (sum, diff, product) = calculate(10, 3);
println!("Sum: {}, Difference: {}, Product: {}", sum, diff, product);
}
Breakdown
1
fn greet(name: &str) -> String
Function taking a string slice, returning a String
2
format!("Hello, {}!", name)
The last expression is implicitly returned
3
fn calculate(x: i32, y: i32) -> (i32, i32, i32)
Returns a tuple of three i32 values
4
let (sum, diff, product) = calculate(10, 3);
Destructures the returned tuple into three variables