Rust Function

ww‮gi.w‬iftidea.com

In Rust, a function is a set of statements that perform a specific task. Functions can take parameters as input, execute a series of statements, and return a value.

Here's an example of a function that takes two integers as input, adds them together, and returns the result:

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

let result = add_numbers(3, 4);
println!("Result: {}", result);

In this example, we're defining a function called add_numbers that takes two parameters x and y of type i32 (i.e., 32-bit signed integers) and returns an i32 value (i.e., the sum of x and y).

We're then calling the add_numbers function with the arguments 3 and 4, and storing the result in a variable called result. Finally, we're printing the value of result using the println! macro.

You can define functions that don't return a value by specifying the () type as the return type. Here's an example:

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

print_greeting("Alice");

In this example, we're defining a function called print_greeting that takes a string slice as a parameter (i.e., a reference to a string) and doesn't return a value. We're then calling the print_greeting function with the argument "Alice", which will print the greeting "Hello, Alice!".

You can also use the return keyword to exit a function early and return a value. Here's an example:

fn get_max(x: i32, y: i32) -> i32 {
    if x > y {
        return x;
    } else {
        return y;
    }
}

let result = get_max(3, 4);
println!("Max value: {}", result);

In this example, we're defining a function called get_max that takes two parameters x and y of type i32 and returns the maximum value of the two. We're using an if statement to check which value is greater and then returning the appropriate value using the return keyword.

We're then calling the get_max function with the arguments 3 and 4, and storing the result in a variable called result. Finally, we're printing the value of result using the println! macro.