我有一大块代码可以打开文件并逐行搜索内容,然后对每个匹配的行执行一些操作。我想将其分解为它自己的函数,该函数获取文件的路径并为您提供匹配的行,但我无法弄清楚如何正确地将其分解。
这是我认为接近的内容,但出现编译器错误:
/// get matching lines from a path
fn matching_lines(p: PathBuf, pattern: &Regex) -> Vec<String> {
let mut buffer = String::new();
// TODO: maybe move this side effect out, hand it a
// stream of lines or otherwise opened file
let mut f = File::open(&p).unwrap();
match f.read_to_string(&mut buffer) {
Ok(yay_read) => yay_read,
Err(_) => 0,
};
let m_lines: Vec<String> = buffer.lines()
.filter(|&x| pattern.is_match(x)).collect();
return m_lines;
}
和编译器错误:
src/main.rs:109:43: 109:52 error: the trait `core::iter::FromIterator<&str>` is not implemented for the type `collections::vec::Vec<collections::string::String>` [E0277]
src/main.rs:109 .filter(|&x| pattern.is_match(x)).collect();
^~~~~~~~~
src/main.rs:109:43: 109:52 help: run `rustc --explain E0277` to see a detailed explanation
src/main.rs:109:43: 109:52 note: a collection of type `collections::vec::Vec<collections::string::String>` cannot be built from an iterator over elements of type `&str`
src/main.rs:109 .filter(|&x| pattern.is_match(x)).collect();
^~~~~~~~~
error: aborting due to previous error
如果我使用String
而不是&str
我得到这个错误:
src/main.rs:108:30: 108:36 error: `buffer` does not live long enough
src/main.rs:108 let m_lines: Vec<&str> = buffer.lines()
^~~~~~
哪种有意义。我猜这些行留在buffer
函数末尾超出范围的行内,因此收集对字符串的引用向量并没有真正帮助我们。
如何返回一组行?