首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >锈菌`borrow_mut`,`borrow_mut`和move

锈菌`borrow_mut`,`borrow_mut`和move
EN

Stack Overflow用户
提问于 2021-06-25 06:16:54
回答 1查看 932关注 0票数 0

我的代码是

代码语言:javascript
复制
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();
}

效果很好。但在这一行:

代码语言:javascript
复制
let source = self.source.borrow_mut();

如果将borrow_mut更改为borrow,将产生错误:

代码语言:javascript
复制
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能工作,但却不能借来。我对moveborrow之间的关系没有一个清晰的理解。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-25 06:40:22

,所以为什么borrow_mut工作,但borrow不工作。

因为there is an implementation of Iterator for exclusive references to iterators

代码语言:javascript
复制
impl<'_, I> Iterator for &'_ mut I where I: Iterator + ?Sized

这意味着对iterator的独占引用本身就是一个迭代器,并且可以被“原样”使用(顺便说一句,这就是为什么Iterator::by_ref是一种东西,并且是有用的)。

我对moveborrow之间的关系没有一个明确的理解。

它本身没有一个迭代器,只是在本例中,对迭代器的可变引用也是迭代器(其本身),这意味着它满足了take_while的要求,即按值获取迭代器:

代码语言:javascript
复制
pub fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where P: FnMut(&Self::Item) -> bool

共享引用不是这样,因此会触发所看到的错误。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68126326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档