Rust:为什么我不能在循环中匹配 mut 字符串选项?

Rust: why can't I pattern match a mut String Option inside a loop?

我这里有这段代码,我尝试根据分隔符提取一些文本:

    //not working
    let mut text: Option<String> = None;
    for d in DELIMITERS {
        let split_res = full_text.split_once(d);
        if let Some((_, t0)) = split_res {
            let t = t0.to_string();
            match text {
                None => text = Some(t),
                Some(t2) => if t.len() < t2.len() {
                    text = Some(t); 
                }
            }
        }
    }

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8e4e0e8d7b2271b8f8ebd126896236ea

但是我从编译器那里得到了这些错误

^^ value moved here, in previous iteration of loop

note: these 2 reinitializations might get skipped

这是怎么回事?

为什么我不能对文本进行模式匹配?问题是我的 text 变量被消耗了吗?我真的无法理解在哪里以及如何?

更改代码以在 text 上使用 as_ref() 修复了错误,但我不明白为什么这是必要的:

    //working
    let mut text: Option<String> = None;
    for d in DELIMITERS {
        let split_res = full_text.split_once(d);
        if let Some((_, t0)) = split_res {
            let t = t0.to_string();
            match text.as_ref() {
                None => text = Some(t),
                Some(t2) => if t.len() < t2.len() {
                    text = Some(t); 
                }
            }
        }
    }

如果您不使用 as_ref,您将移动对象并消耗它,因此它在下一次迭代中不可用。

您还可以匹配参考:

match &text {}

Playground

或者你可以 take 内部值,留下 None ,这样你就不会丢弃它。因为你 re-assignate 它之后保持相同的功能:


const DELIMITERS: [&'static str; 2] = [
    "example",
    "not-found",
];

fn main() {
    let full_text = String::from("This is an example test");
    let mut text: Option<String> = None;
    for d in DELIMITERS {
        let split_res = full_text.split_once(d);
        if let Some((_, t0)) = split_res {
            let t = t0.to_string();
            match text.take() {
                None => text = Some(t),
                Some(t2) => if t.len() < t2.len() {
                    text = Some(t); 
                }
            }
        }
    }
    if let Some(t) = text {
        println!("{}", t);
    }
}

Playground