How to skip lines while using bufreader.lines()

I want just the content below # Description, which is separated from the heading by two newlines.

pub fn extract_description(path: &Path) -> io::Result<String> {
        let mut description = String::new();
        let file = File::open(path)?;
        let reader = BufReader::new(file);

        for line in reader.lines() {
            let line = line?;
            if line.starts_with("# Description") {
                // skip next two lines
            }

            description.push_str(&line);
        }
        Ok(description)
    }

for consumes the iterator, so you can't manipulated in inside the for loop. But you can use while let instead to make the iterator still usable within the loop body.

-    for line in reader.lines() {
+    let mut lines = reader.lines();
+    while let Some(line) = lines.next() {
         let line = line?;
         if line.starts_with("# Description") {
             // skip next two lines
+            // todo: check that they're actually empty
+            let _discard = lines.next();
+            let _discard = lines.next();
         }

         description.push_str(&line);
     }
2 Likes

This is mainly for the sake of an example, but if this pattern occurs many times and you want to later use more iterator combinators, you can implement your own Iterator, which will match items with a given predicate, and then skip it and following ones after match. Here's a link to the playground for a simple example.