“cannot move out of borrowed content” when using s

2019-07-07 19:25发布

I have trouble using a std::iter::Peekable. Why does the following code does not compile?

// rustc 1.7.0-nightly (b4707ebca 2015-12-27)

use std::iter::*;

struct Foo<'a> {
    chars: Peekable<Chars<'a>>,
}

impl<'a> Foo<'a> {
   fn foo(&mut self) {
       self.chars.next(); // Ok
       self.chars.skip_while(|c| true); // error: cannot move out of borrowed content [E0507]
   }
}

标签: rust
1条回答
我命由我不由天
2楼-- · 2019-07-07 19:49

skip_while takes self by value. But chars can't be moved because it's still mutably borrowed by the &mut self. You can use by_ref to make sure the value skip_while gets is a reference to a wrapper, instead.

self.chars.by_ref().skip_while(|c| true);
查看更多
登录 后发表回答