0

I'd like to change the below code to avoid using .unwrap or .expect :

thread::scope(|s| {
    for name in names {
        s.spawn(move |_| {
            let path_to_file = format!("{}{}", base, name.as_str());
            let path_to_file_written = format!("{}{}", guichetout, name.as_str());
            write_file(path_to_file.as_str(), name.as_str(), guichetout)
                .expect("cannot write data");
            log_hash(&path_to_file_written)
                .expect("Cannot write hash !");
        });
    }
})
.unwrap();

I'm currently using crossbeam_utils::thread and I'm thinking about switching to rayon. So I need to change this code into an iterator with various combinators. I've tried a lot of things but nothing works properly. So if anyone can help me, that would be great.

r3dlight
  • 101
  • 8
  • 1
    `names` looks like it already is an iterator. What exactly did you try, and what roadblocks did you hit? – nnnmmm May 22 '20 at 12:28
  • Sorry, I was not clear enough I guess. Yes names is already an iterator but my problem is to find the good combinators to turn this code ready for rayon. I've tried many things with .map, .for_each() but I cannot find a way to make it work chaining all my functions. – r3dlight May 22 '20 at 15:05

1 Answers1

0
  1. Move the innermost code into a function, so that you can easily return Result and use ? operator to handle errors.

  2. Use a channel (std's mpsc channel or crossbeam's faster channel) to send results back. if let Err(e) = fallible() { channel.send(e) }. On another thread you can read from that channel and see whether you get errors, or the channel is closed without errors arriving (success).

Kornel
  • 97,764
  • 37
  • 219
  • 309