WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 5 of 100

How do you create a function in Rust? Provide a simple example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

To create a function in Rust, you need to first declare the function with its name, input parameters, output type, and the code block containing the steps or operations to be executed by the function. Here is an example of a simple function that takes two integer inputs and returns their sum:

    fn add_numbers(x: i32, y: i32) -> i32 {
        let sum = x + y;
        sum
    }

In the above code, we have defined a function with the name ‘add_numbers‘ that takes two integer inputs ‘x‘ and ‘y‘. The output type of the function is also ‘i32‘ (integer). Inside the code block, we have performed the addition operation and stored the result in the variable ‘sum‘. Finally, we are returning the value of ‘sum‘ as the output of the function.

To use this function in our main code, we can call it as follows:

    fn main() {
        let result = add_numbers(10, 20);
        println!("The sum is {}", result);
    }

In the above code, we have called the ‘add_numbers‘ function with the inputs ‘10‘ and ‘20‘, and stored the result in the variable ‘result‘. Finally, we have printed the output using the ‘println‘ function. The output of the program will be:

    The sum is 30
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics