0

In the Rust program below, pair is a vector of Option values, where each Option value is Some ordered pair. My goal is to: (1) extract the first components of these ordered pairs, then (2) sum the distinct values that result from step (1). My attempt at this is shown below:

fn main() {
    let pair: Vec<Option<(u32, Vec<u32>)>> = vec![
        Some((2, vec![1, 0])),
        Some((7, vec![0, 1])),
        Some((7, vec![])),
        Some((3, vec![1, 1])),
        Some((2, vec![0, 1, 0])),
    ];

    let mut values = pair.iter().map(|opt| opt.unwrap().0).collect::<Vec<_>>();
    values.sort();
    values.dedup();
    let distinct_sum: u32 = values.iter().sum();

    println!("The sum of the distinct values should be 2+7+3=12.");
    println!("The sum actually is {}", distinct_sum);
} // end main

But the Rust compiler tells me (regarding opt) that I cannot move out of borrowed content.

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:10:44
   |
10 |     let mut values = pair.iter().map(|opt| opt.unwrap().0).collect::<Vec<_>>();
   |                                            ^^^ cannot move out of borrowed content

Could someone please point me in the right direction in order to achieve the above goal?

E_net4
  • 27,810
  • 13
  • 101
  • 139
user3134725
  • 1,003
  • 6
  • 12
  • 2
    `let mut values = pair.iter().filter_map(|opt| opt.as_ref().map(|x| x.0)).collect::>();` – Stargateur Jun 27 '18 at 04:01
  • 1
    You can use `into_iter()` instead of `iter()` if consuming the input is OK. Else use the solution from the linked question: `opt.as_ref().unwrap()`. – starblue Jun 27 '18 at 09:06

0 Answers0