我的代码是
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之间的关系没有一个清晰的理解。
发布于 2021-06-25 06:40:22
,所以为什么
borrow_mut工作,但borrow不工作。
因为there is an implementation of Iterator for exclusive references to iterators
impl<'_, I> Iterator for &'_ mut I where I: Iterator + ?Sized这意味着对iterator的独占引用本身就是一个迭代器,并且可以被“原样”使用(顺便说一句,这就是为什么Iterator::by_ref是一种东西,并且是有用的)。
我对
move和borrow之间的关系没有一个明确的理解。
它本身没有一个迭代器,只是在本例中,对迭代器的可变引用也是迭代器(其本身),这意味着它满足了take_while的要求,即按值获取迭代器:
pub fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where P: FnMut(&Self::Item) -> bool共享引用不是这样,因此会触发所看到的错误。
https://stackoverflow.com/questions/68126326
复制相似问题