0

The following code is unable to deduce the type of s

fn main() {
    let l: Vec<u32> = vec![];
    let s = l.iter().sum();
    println!("{:?}", s);
}

This is motivated by something in Rust by Example https://rustbyexample.com/std_misc/threads/testcase_mapreduce.html

// collect each thread's intermediate results into a new Vec
let mut intermediate_sums = vec![];
for child in children {
    // collect each child thread's return-value
    let intermediate_sum = child.join().unwrap();
    intermediate_sums.push(intermediate_sum);
}

// combine all intermediate sums into a single final sum.
//
// we use the "turbofish" ::<> to provide sum() with a type hint.
//
// TODO: try without the turbofish, by instead explicitly
// specifying the type of intermediate_sums
let final_result = intermediate_sums.iter().sum::<u32>();

This seems to be implying that this should be possible. Or have I misinterpreted this suggestion?

N.B. I see some related ticket e.g., Why can't Rust infer the resulting type of Iterator::sum?, however in that case there is no type given for the sequence.

tahsmith
  • 1,643
  • 1
  • 17
  • 23

1 Answers1

1

This seems to be implying that this should be possible. Or have I misinterpreted this suggestion?

I think it's a misinterpretation.

// TODO: try without the turbofish, by instead explicitly
// specifying the type of intermediate_sums
let final_result = intermediate_sums.iter().sum::<u32>();

It says you can do without the turbo fish by explicitly specifying the type, that is by doing:

let final_result: u32 = intermediate_sums.iter().sum();

In this respect, your main function can be written as:

fn main() {
    let l: Vec<u32> = vec![];
    let s: u32 = l.iter().sum();
    println!("{:?}", s);
}
mattgathu
  • 1,129
  • 1
  • 19
  • 28
  • Doesn't that read "specifying the type of **intermediate_sums**", ie the array being summed, not the sum result? OP already does that – harmic Mar 13 '18 at 10:27
  • hmmm, I'm not sure. Even with **intermediate_sums** as `Vec`, the compiler still cannot infer type and gives a suggestion "consider giving `final_result` a type" – mattgathu Mar 13 '18 at 11:17