I'd like to implement an error description which uses one of the error's parameters, but I can't find a way to return a description which doesn't disappear.
#[derive(Debug, PartialEq)]
pub struct MissingParamError {
name: Box<String>
}
impl Error for MissingParamError {
fn description(&self) -> &str {
&format!("Missing parameter {}", self.name)
}
}
This of course causes an error due to the generated description going out of scope.
Is there any workaround for this apart from:
MissingParamError::new
which will pre-render full descriptionOption<String>
which would render the description on demand and keep it aroundNo; the method signature simply does not allow you to dynamically construct the string. Also, because it uses &self
(i.e. an immutable pointer), you can't use your second workaround.
Since all types that implement Error
must also implement Display
(whose whole purpose is to format a value for display to the user), that would be the appropriate place to generate a non-trivial message.
Or as you suggested, if you're feeling lazy, do it in MissingParamError::new
.
Actually, you can use the second workaround if you switch to RefCell<Option<String>>
in order to get interior mutability, but that's a bit overkill.
Actually actually, you can't, since you can't get a long-lived borrow from a RefCell
(thanks, @bluss).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With