I'm implementing a code parser in a Parser
struct. I am exposing a pub method lines
to iterate over the lines of code with the comments removed. I want to return a Box<Iterator>
extern crate regex; // 1.0.5
use regex::Regex;
pub struct Parser {
code: String,
}
static comment: Regex = Regex::new(r"//.*$").unwrap();
impl Parser {
pub fn new(code: String) -> Parser {
Parser { code }
}
pub fn lines(&self) -> Box<Iterator<Item = &str>> {
let lines = self
.code
.split("\n")
.map(|line| comment.replace_all(line, ""));
Box::new(lines)
}
}
However, the compiler is giving this error:
error[E0271]: type mismatch resolving `<[closure@src/lib.rs:20:18: 20:54] as std::ops::FnOnce<(&str,)>>::Output == &str`
--> src/lib.rs:21:9
|
21 | Box::new(lines)
| ^^^^^^^^^^^^^^^ expected enum `std::borrow::Cow`, found &str
|
= note: expected type `std::borrow::Cow<'_, str>`
found type `&str`
= note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::str::Split<'_, &str>, [closure@src/lib.rs:20:18: 20:54]>`
= note: required for the cast to the object type `dyn std::iter::Iterator<Item=&str>`
It wants me to use std::borrow::Cow
, but I can't find anything in the Map
docs mentioning this requirement. Why is this necessary? Can I avoid it?