使用匹配结果读取 Rust 中的行

Read lines in Rust with match result

我对 Rust 很陌生,正在尝试实现一些基本的东西。 因此,文档中的示例之一是关于从文本文件中读取行:https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html

示例代码有效(显然...)但我想修改它以添加一些错误处理但编译器抱怨我定义的结果

// the result after -> is not valid...
pub fn read_lines<P>(filename: P) -> std::result::Result<std::io::Lines<std::io::BufReader<std::fs::File>>, std::io::Error>
where P: AsRef<Path>, {
    let file = File::open(filename);
    let file = match file {
        Ok(file) => io::BufReader::new(file).lines(),
        Err(error) => panic!("Problem opening the file: {:?}", error),
    };
}

// this is fine
pub fn read_lines2<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

我尝试了智能感知的不同建议,但没有成功。

知道在 Ok/Err 时如何定义结果吗?

这是您要找的吗?

pub fn read_lines<P>(filename: P) -> std::result::Result<std::io::Lines<std::io::BufReader<std::fs::File>>, std::io::Error>
where P: AsRef<Path>, {
    let file = File::open(filename);
    match file {
        Ok(file) => Ok(io::BufReader::new(file).lines()),
        Err(error) => panic!("Problem opening the file: {:?}", error),
    }
}

我删除了 let file =; 以启用隐式 return,并在快乐路径周围添加了一个 Ok() 包装器。

如果我正确理解你的代码的意图,这里有一个更规范的版本:

use std::fs::File;
use std::io::{self, prelude::*};
use std::path::Path;

pub fn read_lines(filename: &Path) -> io::Lines<io::BufReader<File>> {
    let file = File::open(filename).expect("Problem opening the file");
    io::BufReader::new(file).lines()
}

如果您希望调用者处理任何错误,return 类似于 io::Result<T>std::result::Result<T, io::Error> 的别名),表示可能会失败。但是,如果您决定使用 panic!()Result::expect() 之类的方法在函数内部处理错误,那么就不需要 return a Result 给调用者,因为函数如果没有错误发生,仅 returns 到调用者。