不能通过移动绑定到模式守卫

cannot bind by-move into a pattern guard

如何解决 scannot bind by-move into a pattern guard [E0008] 的问题?

let res = match Some("hi".to_string()) {
    Some(s) if s.len() == 0 => 1,
    _ => 3
};

有没有办法不把条件放在手臂上就改?

在这种情况下,您可以通过引用绑定:

let res = match Some("hi".to_string()) {
    Some(ref s) if s.len() == 0 => 1,
    _ => 3
};

这里的一般问题是移动绑定必须禁止进一步使用原始变量,因为移出会使数据无效。如果守卫是false,则需要使用原始变量来匹配后面的模式,由于移动是非法的。

例如:

fn f(x: Option<String>) {
    match x {
        Some(a) if { drop(a); false } => println!("impossible"),
        Some(b) => println!("whoops, {}", b),
        None => println!("none"),
    }
}

如果xSome,内部的String在决定是否a手臂应该被拿走时被移出并释放,但同样的String 一旦 a 手臂被拒绝,立即再次用于 b 手臂。