Skip to main content
TopMiniSite

Back to all posts

How to Sum A Range Of Numbers In Rust?

Published on
5 min read
How to Sum A Range Of Numbers In Rust? image

Best Rust Programming Books to Buy in October 2025

1 The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

BUY & SAVE
$30.13 $49.99
Save 40%
The Rust Programming Language, 2nd Edition
2 Programming Rust: Fast, Safe Systems Development

Programming Rust: Fast, Safe Systems Development

BUY & SAVE
$43.99 $79.99
Save 45%
Programming Rust: Fast, Safe Systems Development
3 Rust in Action

Rust in Action

BUY & SAVE
$51.42 $59.99
Save 14%
Rust in Action
4 Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)

Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)

BUY & SAVE
$47.04 $59.95
Save 22%
Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)
5 Zero To Production In Rust: An introduction to backend development

Zero To Production In Rust: An introduction to backend development

BUY & SAVE
$49.99
Zero To Production In Rust: An introduction to backend development
6 The Rust Programming Language

The Rust Programming Language

BUY & SAVE
$16.92 $39.95
Save 58%
The Rust Programming Language
7 Rust Atomics and Locks: Low-Level Concurrency in Practice

Rust Atomics and Locks: Low-Level Concurrency in Practice

BUY & SAVE
$33.13 $55.99
Save 41%
Rust Atomics and Locks: Low-Level Concurrency in Practice
8 Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes

Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes

BUY & SAVE
$28.90 $49.99
Save 42%
Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes
+
ONE MORE?

In Rust, you can sum a range of numbers using different approaches. Here is one possible way to achieve this:

  1. Start by defining the lower and upper bounds of the range you want to sum.
  2. Create a mutable variable to store the sum and initialize it to zero.
  3. Use a for loop to iterate over the range of numbers, adding each number to the sum variable.
  4. Finally, print or return the sum.

Here is an example code snippet that demonstrates the above steps:

fn main() { let lower_bound = 1; let upper_bound = 10;

let mut sum = 0;

for num in lower\_bound..=upper\_bound {
    sum += num;
}

println!("The sum of the range {} to {} is: {}", lower\_bound, upper\_bound, sum);

}

In this example, the range we want to sum is from 1 to 10 (inclusive), but you can refactor the code to accommodate any desired range.

How to handle potential overflow when summing a range of numbers in Rust?

In Rust, to handle potential overflow when summing a range of numbers, you can use the wrapping_add method provided by the built-in integer types.

Here's an example that demonstrates how to handle overflow when summing a range of numbers:

fn main() { let nums = [1, 2, 3, 4, 5]; let mut sum: u32 = 0;

for &num in &nums {
    sum = sum.wrapping\_add(num);
}

println!("Sum: {}", sum);

}

In this example, we have an array of numbers nums. We initialize a mutable variable sum to 0. Inside the loop, we use the wrapping_add method to add each number to the sum. The wrapping_add method ensures that if overflow occurs, the value wraps around to the minimum value of the integer type being used. This prevents the program from panicking or crashing due to overflow.

Note that in this example, we used u32 as the integer type. You should choose the appropriate integer type based on the range of values you expect to handle.

Alternatively, you can use the checked_add method instead of wrapping_add. The checked_add method returns None if overflow occurs:

fn main() { let nums = [1, 2, 3, 4, 5]; let mut sum: u32 = 0;

for &num in &nums {
    sum = sum.checked\_add(num).unwrap\_or\_else(|| {
        eprintln!("Overflow occurred!");
        std::process::exit(1);
    });
}

println!("Sum: {}", sum);

}

In this example, if checked_add returns None, it means that overflow occurred. We use the unwrap_or_else method to gracefully handle the None case by printing an error message and exiting the program.

What is the difference between the sum and fold functions in Rust?

In Rust, the sum and fold functions are used to aggregate elements of a collection, but they differ in the way they perform the aggregation.

  1. sum: The sum function is a method defined on iterators that only works on elements that can be summed. It returns the sum of all elements in the iterator, using the Add trait for addition. It doesn't require an initial value and assumes that the iterator is not empty. Example usage:

let values = vec![1, 2, 3, 4]; let sum: i32 = values.iter().sum();

  1. fold: The fold function is a more general-purpose method defined on iterators. It allows you to specify an initial value and a folding function that defines the logic for combining elements. The fold function repeatedly applies the folding function to the previous result and the next element, accumulating a final result. Example usage:

let values = vec![1, 2, 3, 4]; let sum: i32 = values.iter().fold(0, |acc, x| acc + x);

In the example above, the initial value is 0, and the folding function (|acc, x| acc + x) adds each element (x) to the accumulated result (acc).

In summary, sum is a specialized function specifically for summation, while fold is a more general-purpose function that allows you to perform custom aggregations by providing an initial value and a folding function.

What is the effect of using inclusive range syntax when summing numbers in Rust?

In Rust, the inclusive range syntax ..= can be used when summing numbers to include the value at the end of the range.

Here's an example to illustrate the effect of using inclusive range syntax when summing numbers in Rust:

fn main() { let sum_exclusive = (1..10).sum(); println!("Sum (exclusive range): {}", sum_exclusive);

let sum\_inclusive = (1..=10).sum();
println!("Sum (inclusive range): {}", sum\_inclusive);

}

Output:

Sum (exclusive range): 45 Sum (inclusive range): 55

In the above code, the exclusive range 1..10 sums all the numbers from 1 to 9, excluding 10. The sum is 45.

However, the inclusive range 1..=10 includes the number 10 in the range and sums all the numbers from 1 to 10. The sum is 55.

Using the inclusive range syntax allows you to include the end value in the range, resulting in a different calculation or behavior compared to an exclusive range.