w3resource

Rust Function: Calculate Sum of Borrowed integers

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

Write a Rust function that borrows a slice of integers and calculates their sum.

Sample Solution:

Rust Code:

// Define a function named 'calculate_sum' that borrows a slice of integers and returns their sum
fn calculate_sum(numbers: &[i32]) -> i32 {
    // Initialize a variable 'sum' to store the sum of numbers
    let mut sum = 0;

    // Iterate over each element of the slice and add it to 'sum'
    for &num in numbers {
        sum += num;
    }

    sum // Return the sum
}

fn main() {
    let numbers = [1, 2, 3, 4, 5]; // Define an array of integers

    // Call the 'calculate_sum' function and pass a reference to 'numbers' to borrow it
    let sum = calculate_sum(&numbers);

    // Print the sum of all numbers in the slice
    println!("Sum of numbers: {}", sum);
}

Output:

Sum of numbers: 15

Explanation:

Here is a brief explanation of the above Rust code:

  • fn calculate_sum(numbers: &[i32]) -> i32 { ... }: This is a function named calculate_sum that borrows a slice of integers (&[i32]) and returns their sum as an integer (i32). The parameter numbers is of type &[i32], indicating borrowing.
  • Inside the function:
    • We initialize a variable 'sum' to store the sum of numbers.
    • We iterate over each element 'num' of the slice using a "for" loop, adding each element to 'sum'.
  • We return the value of 'sum'.
  • In the main function,
    • Define an array of named 'numbers' containing some integers.
    • Call the calculate_sum function and pass a reference to the array (&numbers) to borrow it.
    • Finally, we print the sum of all numbers in the array slice returned by the function.

Rust Code Editor:

Previous: Rust Function: Take Tuple Ownership, Return element.
Next: Rust Function: Borrow Slice, Calculate Sum.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-6.php