【发布时间】:2020-12-18 17:56:12
【问题描述】:
我一直在关注here。
它包含一个看似相关的简化示例,但我的实现并不适合。这里的错误是:returns a reference to data owned by the current function。该示例建议使用结构的特定属性,即String。这很好,因为编译器可以知道该结构将持续多长时间。但是如果我们需要在运行时构建字符串呢?我该如何完成这项工作?
#[derive(Clone, Debug)]
pub enum ReadFailure {
MissingFile(String),
BadData(String),
// ...
}
impl fmt::Display for ReadFailure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReadFailure::MissingFile(path) => write!(f, "WARNING - File not read (file does not exist): {}", path),
ReadFailure::BadData(path) => write!(f, "WARNING - File cannot be read (file has bad data): {}", path),
// ...
}
}
}
/// Implements an error for failure to read with a message
#[derive(Clone, Debug)]
pub struct ReadError {
/// Failure condition
error: ReadFailure,
}
impl fmt::Display for ReadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.error)
}
}
impl Error for ReadError {
fn description(&self) -> &str {
let s = format!("{}", self.error);
&s
}
}
【问题讨论】:
-
您不必实现
description。 rustdoc 说:“自 1.42.0 起已弃用:使用 Display impl 或 to_string()”doc.rust-lang.org/std/error/trait.Error.html#method.description。在实现Display时您将拥有更大的灵活性,即您可以在Formatter上使用write_str 方法。 -
@justinas 我要试试这个,但我认为这正是我需要知道的。非常感谢!
标签: error-handling rust traits lifetime borrow-checker