【发布时间】:2015-09-28 04:32:19
【问题描述】:
我有一大段代码可以打开文件并逐行搜索内容,然后对每个匹配的行执行一些操作。我想将其分解为它自己的函数,该函数获取文件的路径并为您提供匹配的行,但我不知道如何正确地分解它。
这是我认为很接近的内容,但出现编译器错误:
/// 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 内,因此收集对字符串的引用向量并不能真正帮助我们。
如何返回一组行?
【问题讨论】:
标签: rust borrow-checker