这段代码:
fn t(r: &[u8]) {
match r {
_ if r.iter().any(|&x| x == b';') => {}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
给我错误:
error[E0301]: cannot mutably borrow in a pattern guard
|
10 | _ if r.iter().any(|&x| x == b';') => {}
| ^^^^^^^^ borrowed mutably in pattern guard
Run Code Online (Sandbox Code Playgroud)
我知道我不能在匹配模式中可靠地借用,但是为什么编译器认为可以r.iter()借用?有一种iter_mut可变借用的单独方法.
如何在不引入单独功能的情况下检查&[u8]包含b';'?
错误信息有点细微差别 - iter不会相互借用,但结果iter是可变地借用.这是因为Iterator::any需要self通过可变参考:
fn any<F>(&mut self, f: F) -> bool
where
F: FnMut(Self::Item) -> bool,
Run Code Online (Sandbox Code Playgroud)
这是一个复制品:
struct X;
impl X {
fn new() -> X { X }
fn predicate(&mut self) -> bool { true }
}
fn main() {
match () {
_ if X::new().predicate() => {}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
我只是检查切片contains的值是否:
fn t(r: &[u8]) {
match r {
_ if r.contains(&b';') => {}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,这是借用检查员过于激进的一个例子.从比赛后卫的"外线"中相互借用一些东西是一个坏主意,但是可变地借用比赛后卫中创造的东西应该是安全的.
当借用检查器被重写为使用Rust的MIR层时,这种特殊情况很可能会起作用.
也可以看看:
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |