Function Definition in Rust

 

Functions: The Secret Sauce of Clean Code 

Ever written the same code multiple times? That’s like making a sandwich one ingredient at a time for every single bite!  Rust functions save you from that madness by letting you write once, use many times. Let’s break it down! 

1. Declaring a Function 

In Rust, functions are defined using the fn keyword. Here’s a basic example:

fn say_hello() {
    println!("Hello, Rustacean! ");
}

fn main() {
    say_hello();
}

fn declares a function.  say_hello() is the function name.  println! prints a message.  The function is called inside main().

2. Functions with Parameters 

Want to customize your function? Use parameters!

fn greet(name: &str) {
    println!("Hello, {}! ", name);
}

fn main() {
    greet("Alice");
    greet("Bob");
}

 name: &str specifies a string reference parameter.  Call greet("Alice"), and it prints Hello, Alice!.

3. Returning Values from Functions 

Functions can return values using ->.

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    let result = add(3, 5);
    println!("Sum: {}", result);
}

 -> i32 means the function returns an integerNo return keyword needed if the last expression is the return value!

4. Multiple Return Values with Tuples 

Rust can return multiple values using tuples.

fn swap(x: i32, y: i32) -> (i32, i32) {
    (y, x)
}

fn main() {
    let (a, b) = swap(10, 20);
    println!("Swapped: a = {}, b = {}", a, b);
}

Tuples let you return multiple values efficiently.

Wrapping Up 

Now you know:  How to define functions in Rust.  How to pass parameters.  How to return values (even multiple values!).

Post a Comment

0 Comments