error-handling - 用于错误检查的面向对象设计模式

标签 error-handling io rust

我编写了以下读取文本文件内容的函数,如果遇到错误,则 panic!s。

fn get_file_contents(name: String) -> Result<String, io::Error> {
    let mut f = try!(File::open(name));
    let mut contents = String::new();
    try!(f.read_to_string(&mut contents));
    Ok(contents)
}

并且使用以下方法从 Result 中提取内容:

let file_contents = match get_file_contents(file_name) {
    Ok(contents) => contents,
    Err(err) => panic!("{}", err)
};

我现在正尝试使用结构和实现以面向对象的方式重新实现它。我创建了以下结构:

struct FileReader {
    file_name: String,
    file_contents: String,
}

并实现了以下方法:

impl FileReader {
    fn new(fname: &str) -> FileReader {
        FileReader {
            file_name: fname.to_string(),
            file_contents: String::new(),
        }
    }

    fn get_file_contents(&mut self) {
        let mut f = match File::open(&self.file_name) {
            Ok(file) => file,
            Err(err) => panic!("{}", err)
        };

        match f.read_to_string(&mut self.file_contents) {
            Ok(size) => size,
            Err(err) => panic!("{}", err)
        };
    }
}

在 OO 方法中,我没有使用 try! 宏,因为我不希望该方法返回任何值。我的 get_file_contents 的 OO 实现是实现此功能的典型方式吗?如果没有,您能否建议一种替代方法?

最佳答案

In the OO approach, I haven't used the try! macro as I don't want the method to return any value.

不清楚为什么您认为“面向对象”意味着“不返回值”。如果可能发生错误,代码应指出这一点。

许多语言都有与异常 等价的东西——从函数或方法中抛出(也称为“返回”)的带外值。请注意,这意味着这些语言允许从给定函数返回两种不相交的类型:“正常”类型和“异常”类型。这与 Rust 的 Result 非常接近。 : Result<NormalType, ExceptionalType> .

Exceptional 不是一个很好的术语,因为您应该预计打开文件会失败。它有无数种方法无法奏效,但只有一小部分方法可以成功。

panic 更接近于“现在杀死整个程序/线程”。与 C 不同,您被迫要么处理问题,将其返回给调用者,要么终止程序( panic )。

如果您使用支持它们的语言抛出异常,请使用 Result .如果您会终止程序,或者不想处理错误,请使用 panic。


如果您想在特定情况下 panic ,请使用 unwrap ,甚至更好,expect :

fn get_file_contents(&mut self) {
    let mut f = File::open(&self.file_name).expect("Couldn't open file");
    f.read_to_string(&mut self.file_contents).expect("Couldn't read file");
}

seems kind of clunky to have to deal with the Result for each method.

这就是为什么 Error Handling section of The Rust Programming Language花了大量时间讨论 try!宏观:

A cornerstone of error handling in Rust is the try! macro. The try! macro abstracts case analysis like combinators, but unlike combinators, it also abstracts control flow. Namely, it can abstract the early return pattern seen above.

(这在页面上下文中更有意义)

I don't want my code to try and recover from the error (most likely caused by the file not being found) - I want it to print a useful error message and then die

然后一定要 panic 。有更简洁和更详细的方法来做到这一点(如上所示)。

关于error-handling - 用于错误检查的面向对象设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165707/

相关文章:

reactjs - Apollo GraphQL 本地和全局错误处理

c - 文件读取问题 - 平行版生命游戏

rust - 如何避免使用 IntoParallelIterator 绑定(bind)的可变和不可变借用

rust - 我将如何在 Rust 中创建句柄管理器?

ios - stripe iOS 集成中的creditCard.validateCardReturningError(&error)

objective-c - iOS - EXC_BAD_ACCESS 错误

c# - 转换位置时出现Unity3d错​​误

file - Haskell读取文件行

hadoop - 在 Windows 7 上构建 Hadoop

rust - 如何创建一个全局的、可变的单例?