如何获得一个函数来返回类似字符串的Vec?

时间:2015-09-28 04:32:20

标签: rust borrow-checker

我有一大堆代码打开文件并逐行搜索内容,然后对每个匹配行执行操作。我想把它考虑到它自己的函数中,它接受一个文件的路径并给你匹配的行,但我无法弄清楚如何正确地考虑它。

这里我认为很接近,但是我收到编译错误:

/// 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里面,它超出了函数末尾的范围,因此收集一个对字符串的引用向量并不能帮助我们。

如何返回一组行?

2 个答案:

答案 0 :(得分:5)

您可以使用String函数将字符串切片转换为拥有的map个对象。

let m_lines: Vec<String> = buffer.lines()
        .filter(|&x| pattern.is_match(x))
        .map(|x| x.to_owned())
        .collect();

然后,您应该可以从函数返回m_lines

答案 1 :(得分:5)

让我们从这个版本开始,该版本在Rust Playground上运行(在提问时提出MCVE是一个好主意):

use std::path::PathBuf;
use std::fs::File;
use std::io::Read;

fn matching_lines(p: PathBuf, pattern: &str) -> Vec<String> {
    let mut buffer = String::new();
    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| x.contains(pattern)).collect();
    return m_lines;
}

fn main() {
    let path = PathBuf::from("/etc/hosts");
    let lines = matching_lines(path, "local");    
}

让我们看一下str::lines的签名:

fn lines(&self) -> Lines // with lifetime elision
fn lines<'a>(&'a self) -> Lines<'a> // without

我首先在源代码中展示了它的样子,以及你可以在心理上把它翻译成第二个。它将返回由您已阅读的String支持的字符串切片的迭代器。这是一件好事,因为它非常有效,因为只需要进行一次分配。但是,你不能return an owned value and a reference to that value at the same time。最简单的方法是将每一行转换为一个拥有的字符串,如Benjamin Lindley所示:

let m_lines: Vec<String> =
    buffer
    .lines()
    .filter(|&x| x.contains(pattern))
    .map(ToOwned::to_owned)
    .collect();

这可以让您的代码进行编译,但它仍然可以更好。您的match语句可以替换为unwrap_or,但由于您完全忽略了错误情况,因此您也可以使用_

let _ = f.read_to_string(&mut buffer);

请注意,真的不是一个好主意。错误对于报告很重要,如果您需要报告错误,丢失错误会咬你!使用unwrap可能更安全,并在发生错误时让程序死掉。

接下来,除非您需要,否则请勿使用明确的return语句,并且不提供类型注释。由于函数返回Vec<String>,因此可以用最后两行替换:

buffer
    .lines()
    .filter(|&x| x.contains(pattern))
    .map(ToOwned::to_owned)
    .collect()

您也可以对p接受的类型更加开放,以便更好地匹配File::open支持的内容:

fn matching_lines<P>(p: P, pattern: &str) -> Vec<String>
    where P: AsRef<Path>

所有在一起:

use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::Read;

fn matching_lines<P>(p: P, pattern: &str) -> Vec<String>
    where P: AsRef<Path>
{
    let mut buffer = String::new();
    let mut f = File::open(p).unwrap();
    let _ = f.read_to_string(&mut buffer);

    buffer
        .lines()
        .filter(|&x| x.contains(pattern))
        .map(ToOwned::to_owned)
        .collect()
}

fn main() {
    let path = PathBuf::from("/etc/hosts");
    let lines = matching_lines(path, "local");
    println!("{:?}", lines);
}