[英]Why does iter borrow mutably when used in a pattern guard?
This code: 这段代码:
fn t(r: &[u8]) {
match r {
_ if r.iter().any(|&x| x == b';') => {}
_ => {}
}
}
gives me the error: 给我错误:
error[E0301]: cannot mutably borrow in a pattern guard
|
10 | _ if r.iter().any(|&x| x == b';') => {}
| ^^^^^^^^ borrowed mutably in pattern guard
I understand that I can not borrow mutably in match patterns, but why does the compiler think that r.iter()
borrows mutably? 我知道我不能在匹配模式中可靠地借用,但为什么编译器认为r.iter()
接受? There is a separate method iter_mut
for borrowing mutably. iter_mut
有一个单独的方法可供借用。
And how can I check that &[u8]
contains b';'
我怎样才能检查&[u8]
包含b';'
without introducing separate functions? 没有引入单独的功能?
The error message is a bit more nuanced — iter
doesn't borrow mutably, but the result of iter
is being borrowed mutably . 该错误消息是一个比较微妙的- iter
不性情不定地借用,但结果iter
正在性情不定地借来的 。 This is because Iterator::any
takes self
by mutable reference: 这是因为Iterator::any
通过可变引用获取self
:
fn any<F>(&mut self, f: F) -> bool
where
F: FnMut(Self::Item) -> bool,
Here's a reproduction: 这是一个复制品:
struct X;
impl X {
fn new() -> X { X }
fn predicate(&mut self) -> bool { true }
}
fn main() {
match () {
_ if X::new().predicate() => {}
_ => {}
}
}
I'd just check if the slice contains
the value: 我只是检查切片是否contains
值:
fn t(r: &[u8]) {
match r {
_ if r.contains(&b';') => {}
_ => {}
}
}
Realistically, this is an example of the borrow checker being overly aggressive. 实际上,这是借用检查员过于激进的一个例子。 Mutably borrowing something from "outside" the match guard is a bad idea, but mutably borrowing something created in the match guard should be safe. 从比赛后卫的“外线”中相互借用一些东西是一个坏主意,但是可变地借用比赛后卫中创造的东西应该是安全的。
It's likely that this particular case would work when the borrow checker is rewritten to use Rust's MIR layer. 当借用检查器被重写为使用Rust的MIR层时,这种特殊情况很可能会起作用。
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.