← 中文资源

简体中文版本

用 mem::replace 与 mem::take 原地切换枚举状态

通过 std::mem::replace 从可变枚举引用中零拷贝取出所有权数据并切换为新状态,同时配合 mem::take 清空待处理队列。

阅读英文原文

实现说明

活动部件是函数 flush_batch、main。 通过 match 做模式匹配,值的每种形态都必须被处理。

使用要点

  • 只用内建 API,没有需要审查的供应链。
  • 演示输出是带标签的(taken=、flushed items=、second flush=),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 flush_batch。

常见问题

运行「用 mem::replace 与 mem::take 原地切换枚举状态」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 taken=、flushed items=、second flush= 标签标明各步骤。

主签名形如 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()
    }
}

代码示例

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:?}");
}