Functions That Talk Back!
What’s better than a function that just runs? A function that takes input and gives output! In Rust, you can pass parameters to functions and get meaningful return values. Let's dive in!
1. Passing Parameters to Functions
Parameters let you send values into functions, making them reusable and dynamic.
a) Single Parameter Function
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Alice");
greet("Bob");
}
The function greet
takes a string reference (&str
) as a parameter. It prints a customized greeting based on the input.
b) Multiple Parameters Function
fn add(a: i32, b: i32) {
println!("The sum of {} and {} is {}", a, b, a + b);
}
fn main() {
add(5, 10);
add(20, 30);
}
Functions can take multiple parameters separated by commas. Parameters must have explicit types in Rust.
2. Returning Values
Functions can return values using ->
followed by the return type.
a) Function with a Return Value
fn square(num: i32) -> i32 {
num * num
}
fn main() {
let result = square(4);
println!("4 squared is {}", result);
}
-> i32
specifies that the function returns an integer. No return
keyword is needed when the last expression is the return value.
b) Using return
Explicitly
fn subtract(a: i32, b: i32) -> i32 {
return a - b; // Explicit return
}
fn main() {
let result = subtract(10, 4);
println!("10 minus 4 is {}", result);
}
Explicit return
is optional unless inside a loop or early return cases.
3. Returning Multiple Values with Tuples
Rust allows returning multiple values by using tuples.
fn min_max(a: i32, b: i32) -> (i32, i32) {
if a < b { (a, b) } else { (b, a) }
}
fn main() {
let (small, large) = min_max(42, 7);
println!("Smaller: {}, Larger: {}", small, large);
}
Tuples allow returning multiple values efficiently. Use destructuring (let (x, y) = ...
) to extract values easily.
Wrapping Up
Now you know: How to pass parameters to functions. How to return values from functions. How to return multiple values using tuples.
0 Comments