【发布时间】:2021-06-25 06:16:54
【问题描述】:
我的代码是
struct Test<Source>
where
Source: Iterator<Item = char>,
{
source: Source,
}
impl<Source: Iterator<Item = char>> Test<Source> {
fn read(&mut self) {
while let Some(item) = self.source.next() {
match item {
'#' => self.read_head(),
_ => {}
}
println!("Handled char {}", item);
}
}
fn read_head(&mut self) {
println!("Start read heading");
let source = self.source.borrow_mut();
let level = source.take_while(|&char| char == '#').count();
println!("Done, level is {}", level);
}
}
fn main() {
let str = "##### Hello World".to_string();
let str = str.chars().into_iter();
let mut test = Test { source: str };
test.read();
}
效果很好。但在这一行:
let source = self.source.borrow_mut();
如果把borrow_mut改成borrow,会报错:
error[E0507]: cannot move out of `*source` which is behind a shared reference
--> src/main.rs:24:21
|
24 | let level = source.take_while(|&char| char == '#').count();
| ^^^^^^ move occurs because `*source` has type `Source`, which does not implement the `Copy` trait
那么为什么 borrow_mut 有效但借用无效。我对move和borrow之间的关系不是很清楚。
【问题讨论】:
标签: rust move borrow-checker