Bil*_*ain 21 pattern-matching rust
如何解决的问题cannot bind by-move into a pattern guard [E0008]上s?
let res = match Some("hi".to_string()) {
Some(s) if s.len() == 0 => 1,
_ => 3
};
Run Code Online (Sandbox Code Playgroud)
有没有改变它而没有把条件放在手臂?
huo*_*uon 32
在这种情况下,您可以通过引用绑定:
let res = match Some("hi".to_string()) {
Some(ref s) if s.len() == 0 => 1,
_ => 3
};
Run Code Online (Sandbox Code Playgroud)
这里的一般问题是,移动绑定必须禁止进一步使用原始变量,因为移出会使数据无效.如果守卫是false,那么原始变量需要用于匹配后来的模式,这是由于移动而非法.
例如:
fn f(x: Option<String>) {
match x {
Some(a) if { drop(a); false } => println!("impossible"),
Some(b) => println!("whoops, {}", b),
None => println!("none"),
}
}
Run Code Online (Sandbox Code Playgroud)
如果x是Some,则String在确定是否a应该采取手臂时将内部移出并解除分配,但是一旦手臂被拒绝,String则立即再次使用该b手臂a.
| 归档时间: |
|
| 查看次数: |
4428 次 |
| 最近记录: |