Pair Drained State With Option::take And zip

Transfer ownership of a pending queue via Option::take so repeated flushes are no-ops, then pair drained jobs with worker slots using Iterator::zip.

RustResilience

Code

snippet
struct Dispatcher {
    pending: Option<Vec<&'static str>>,
}

impl Dispatcher {
    fn flush_to(&mut self, slots: &mut [Option<&'static str>]) -> Vec<&'static str> {
        let Some(jobs) = self.pending.take() else {
            return Vec::new();
        };
        let mut iter = jobs.into_iter();
        // Put slots first so zip stops before pulling an extra job from iter
        for (slot, job) in slots.iter_mut().zip(iter.by_ref()) {
            *slot = Some(job);
        }
        iter.collect()
    }
}

fn main() {
    let mut disp = Dispatcher {
        pending: Some(vec!["job-a", "job-b", "job-c", "job-d"]),
    };
    let mut workers = [None, None];

    let leftover = disp.flush_to(&mut workers);
    println!("assigned slots: {workers:?}");
    println!("unscheduled:    {leftover:?}");

    let second = disp.flush_to(&mut workers);
    println!("second flush:   {second:?} (pending={:?})", disp.pending);
}

Annotated execution — Pair Drained State With Option::take And zip

The snippet is organized around the functions flush_to and main.

The loop for (slot, job) in slots.iter_mut().zip(iter.by_ref()) is the only repeated construct.

Points of care

  • No dependencies section needed; the standard library is the whole story.

Putting it to use

Entry signature: fn flush_to(&mut self, slots: &mut [Option<&'static str>]) -> Vec<&'static str>

The run prints assigned slots:, unscheduled:, second flush: — each prefix names the step that produced it.

main calls 1 helper in sequence: flush_to.

Core lines

let Some(jobs) = self.pending.take() else {
    return Vec::new();
};
for (slot, job) in slots.iter_mut().zip(iter.by_ref()) {
    *slot = Some(job);
}
let mut workers = [None, None];

Interactive Tools for This Topic

FAQ

What does Pair Drained State With Option::take And zip print when run?
Run it as a complete program — the output lines carry labels such as `assigned slots:`, `unscheduled:`, `second flush:`.