I was following along here: https://stevedonovan.github.io/rust-gentle-intro/6-error-handling.html#basic-error-handling
It contains an simplified example which seemed relevant, but my implementation doesn't lend itself well. The error here when compiling for description
is: returns a reference to data owned by the current function
. The example suggests using a specific attribute of a struct, which is a String. I think the reason that this is fine in the example because the compiler can know how long that struct will last. But what if we need to build the string at runtime? How do I make this work?
#[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
}
}