Is there a way to have a Rust closure that moves only some variables into it?

后端 未结 2 1414
小蘑菇
小蘑菇 2020-12-10 07:49

I have a general struct with settings and an extra variable setting that I want to tune and play around with.

For all possible values in an integer ra

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 08:16

    Yes, it is possible to move only one or some variables into a closure (rather than all or none).

    Yes, this can be used to "circumvent" reference counting.

    I found an answer in the documentation of rayon::scope that turns out to be exactly about this problem: 'Accessing the stack data [from within a scoped threads scope]'. That page also has an example that is clearer than the pseudocode in this question.

    It turns out that you can either:

    • Use a move closure but refer to variables in the outer scope by shadowing them with a reference, therefore capturing them by reference rather than by value, using let settings = &settings:

      crossbeam::scope(|scope| {
          let settings = &settings; // refer to outer variable by reference
          for score in 0..MAX_FEASIBLE_SCORE {
              scope.spawn(move |_| {
                  let work_result = do_cool_computation(settings, score);
                  println!("{:?}", work_result);
              });
          }
      })
      .unwrap();
      
    • Use a normal closure, and only move the required variables by shadowing them inside the closure using let score = score:

      crossbeam::scope(|scope| {
          for score in 0..MAX_FEASIBLE_SCORE {
              scope.spawn(|_| {
                  let score = score; // capture only score
                  let work_result = do_cool_computation(&settings, score);
                  println!("{:?}", work_result);
              });
          }
      })
      .unwrap();
      

提交回复
热议问题