DEV Community

Daniel Imfeld
Daniel Imfeld

Posted on • Originally published at imfeld.dev

1 1

Selective Closure Capture in Rust

Sometimes in Rust you have a closure that needs to move some values but not others. If all the values satisfy the Copy trait this isn't an issue, but that is usually not the case.

You can solve this problem by creating new bindings for the by-reference values, so that the closure moves the references instead of the original value. It’s not pretty but it works well.

let threads = vec![("referrers", "s"), ("referrals", "o")];

crossbeam::thread::scope(|s| {
    for &(description, field) in &threads {
        // Get variables that we want to borrow explicitly as references so
        // that the closure moves only the references.
        let input_path = &input_path;
        let output_path = &output_path;
        let logger = &logger;
        let file_prefix = &file_prefix;
        s.spawn(move |_| {
            write_data(
                &logger,
                description,
                &input_path,
                &output_path,
                file_prefix.as_str(),
                field
            );
        });
    }
})
.unwrap();
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs