Ganesh11
Ganesh11

Reputation: 129

cannot be built from an iterator over elements of type `()`

This program is for printing parallel running thread. Print all start thread before end thread. But this program throw error the trait FromIterator<()> is not implemented for Vec<JoinHandle<>> the trait FromIterator<T> is implemented for Vec<T>. What's wrong with this program? Any feedback helps a lot.

let handles: Vec<JoinHandle<String>> = (0..=10).map(|i| {
        let delay = rand::thread_rng().gen_range(10..=2000);
        let builder =
          thread::Builder::new().name(format!("Thread-{}", i));
        
        builder.spawn(move || {
          println!(
            "thread started = {}",
            thread::current().name().unwrap()
          );
          thread::sleep(Duration::from_millis(delay));
          thread::current().name().unwrap().to_owned()
        }).unwrap();
      }).collect();

for h in handles {
  let r = h.join().unwrap();
  println!("thread done = {:?}", r);
}

rust-playground

Upvotes: 1

Views: 168

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

If you want the last value of a function (be it a top-level function or a closure) to be returned implicitly, you should not end it with a semicolon. Semicolons terminate statements that are being run for effects, not the final expression of a returning function. Replace

builder.spawn(move || {
  ...
}).unwrap();

with

builder.spawn(move || {
  ...
}).unwrap() // <- No semicolon :)

Upvotes: 1

Related Questions