Transition Enum State In Place With mem::replace
Extract owned vectors from a mutable enum variant using std::mem::replace and drain buffers via std::mem::take without cloning.
Code
use std::mem;
#[derive(Debug)]
enum BatchState {
Collecting(Vec<String>),
Flushed(usize),
}
fn flush_batch(state: &mut BatchState) -> Vec<String> {
match mem::replace(state, BatchState::Flushed(0)) {
BatchState::Collecting(items) => {
*state = BatchState::Flushed(items.len());
items
}
BatchState::Flushed(count) => {
*state = BatchState::Flushed(count);
Vec::new()
}
}
}
fn main() {
let mut pending = vec!["evt-a".to_string(), "evt-b".to_string()];
// mem::take moves the Vec out and leaves an empty Vec behind
let taken = mem::take(&mut pending);
println!("taken={taken:?}, pending={pending:?}");
let mut state = BatchState::Collecting(taken);
let batch = flush_batch(&mut state);
println!("flushed items={batch:?}, state={state:?}");
let second = flush_batch(&mut state);
println!("second flush={second:?}, state={state:?}");
}Inside the implementation — Transition Enum State In Place With mem::replace
Follow the control path entering functions flush_batch and main, doing all the work.
Pattern matching via match forces each shape of the value to be handled.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Using it
Entry signature: fn flush_batch(state: &mut BatchState) -> Vec<String>
The run prints taken=, flushed items=, second flush= — each prefix names the step that produced it.
Execute the file and main walks through flush_batch, in that order.
Key statements
match mem::replace(state, BatchState::Flushed(0)) {
BatchState::Collecting(items) => {
*state = BatchState::Flushed(items.len());
items
}
BatchState::Flushed(count) => {
*state = BatchState::Flushed(count);
Vec::new()
}
}
Interactive Tools for This Topic
FAQ
- What does Transition Enum State In Place With mem::replace print when run?
- Run it as a complete program — the output lines carry labels such as `taken=`, `flushed items=`, `second flush=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.