如何解决Rust `borrow_mut`、`borrow_mut` 和移动
我的代码是
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
之间的关系不是很清楚。
解决方法
那么为什么 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::by_ref
是一个东西,而且很有用)。
我对 move
和 borrow
之间的关系不是很清楚。
本身并没有一个,只是在这种情况下,对迭代器的可变引用也是迭代器(就其本身而言),这意味着它满足 take_while
的要求按值迭代器:
pub fn take_while<P>(self,predicate: P) -> TakeWhile<Self,P> where P: FnMut(&Self::Item) -> bool
共享引用并非如此,因此会触发您看到的错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。