0

I'm trying to implement a "read line" function by implementing the Iterator trait.

Here, I own the Bytes<BufReader<File>> inside the struct. For the next function, I wish to loop over the iterator to find a b'\n'.

use std::io::BufReader;

struct MyStringLineBufReader {
    bytes_iter: std::io::Bytes<BufReader<std::fs::File>>,
}

impl Iterator for MyStringLineBufReader {
    type Item = (String);

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        let mut bytes: Vec<u8> = Vec::new();
        for b in self.bytes_iter {
            let b = b.unwrap();
            if b == b'\n' {
                break;
            } else {
                bytes.push(b)
            }
        }
        return Some(String::from_utf8(bytes).unwrap());
    }
}

The code is not finished yet but I feel it should compile. I get the following message:

error[E0507]: cannot move out of borrowed content
  --> src/lib.rs:12:18
   |
12 |         for b in self.bytes_iter {
   |                  ^^^^ cannot move out of borrowed content

I don't know how to fix this.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sanhu Li
  • 402
  • 5
  • 11
  • The duplicates applied to your situation: `for b in &mut self.bytes_iter` / `for b in self.bytes_iter.by_ref()` – Shepmaster Oct 17 '18 at 03:10
  • @Shepmaster Really appreciate your help. That works! Would you please send me the duplicated question if possible? I wish to read more about it. – Sanhu Li Oct 17 '18 at 03:40
  • the duplicate questions are listed in a box on this page; try reloading your browser. – Shepmaster Oct 17 '18 at 03:59

0 Answers0