w3resource

Rust Function: Borrowed integers sum

Rust Ownership, Borrowing, and Lifetimes: Exercise-10 with Solution

Write a Rust function that borrows two integers and returns their sum.

Sample Solution:

Rust Code:

// Define a function named 'sum_of_integers' that borrows two integers and returns their sum
fn sum_of_integers(a: &i32, b: &i32) -> i32 {
    *a + *b // Dereference the integers and return their sum
}

fn main() {
    let num1 = 10;
    let num2 = 20;

    // Call the 'sum_of_integers' function and pass references to 'num1' and 'num2' to borrow them
    let result = sum_of_integers(&num1, &num2);

    // Print the result of the sum
    println!("Sum of {} and {} is: {}", num1, num2, result);
}

Output:

Sum of 10 and 20 is: 30

Explanation:

Here is a brief explanation of the above Rust code:

  • fn sum_of_integers(a: &i32, b: &i32) -> i32 { ... }: This is a function named sum_of_integers that borrows two integers (&i32) and returns their sum as an integer (i32). The parameters 'a' and 'b' are references to integers, indicating borrowing.
  • Inside the function:
    • We dereference 'a' and 'b' using the "*" operator to access the values they point to.
    • We add the dereferenced integers and return their sum.
  • In the main function,
    • Define two integers 'num1' and 'num2'.
    • Call the "sum_of_integers()" function and pass references to 'num1' and 'num2' using & to borrow them.
    • Finally we print the result of the sum.

Rust Code Editor:

Previous: Rust Function: Double Vector length, Ownership transfer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.