1

I have a min-heap of i32 in Rust, and I want to calculate the sum of its elements and store it in i32.

let mut total_sum = 0;
for current in min_heap {
    total_sum = current + total_sum;
}

I am getting the following error when compiling:

cannot add `{integer}` to `Reverse<i32>` 
Peter Hall
  • 53,120
  • 14
  • 139
  • 204

2 Answers2

2

You can use the tuple accessor, .0, or use destructuring.

let mut total_sum = 0;
for current in min_heap {
    total_sum += current.0;
}

Or with destructuring:

let mut total_sum = 0;
for Reverse(current) in min_heap {
    total_sum += current;
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
2

You can simply call the sum method on your iterator after mapping Reverse<i32>'s inside your heap to their inner values.

let total_sum: i32 = min_heap.into_iter()
                            .map(|i| i.0)
                            .sum();

Some advices:

  1. Avoid mutations;
  2. Don't use x = x + y, use x += y instead;
  3. Don't use camelCase in function and variable names;
  4. Don't use new-line braces.
Miiao
  • 751
  • 1
  • 8