Google News
logo
Rust - Interview Questions
How do you define a function in Rust?
In Rust, you can define functions using the `fn` keyword followed by the function name, parameter list, return type, and a code block. Here's the basic syntax for defining a function in Rust:
fn function_name(parameter1: Type1, parameter2: Type2) -> ReturnType {
    // Function body
    // Code goes here
    // Optional return statement
    // Last expression is implicitly returned
}​

Let's break down each component :

* `fn`: The keyword used to declare a function.

* `function_name`: The name of the function, following Rust's naming conventions.

* `parameter1`, `parameter2`: The function's parameters, each specified with its name followed by a colon and the parameter type.

* `ReturnType` : The return type of the function, specified after the parameter list using the `->` arrow notation.

* Function body : The code block enclosed in curly braces `{}` that contains the statements and expressions defining the function's behavior.
* Return statement : An explicit `return` statement can be used to return a value from the function. However, in Rust, the last expression of the function is implicitly returned as the result.

Here's an example function that calculates the sum of two integers and returns the result :
fn add(a: i32, b: i32) -> i32 {
    let sum = a + b;
    sum  // The last expression is implicitly returned
}​

You can then call the function as follows :
let result = add(3, 5);
println!("Result: {}", result);​

This would output : `Result: 8`.

In addition to regular functions, Rust also supports closures, which are anonymous functions that can capture and use variables from their surrounding environment. Closures are defined using the `|parameter1, parameter2|` syntax.
Advertisement