Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Error description with own string

Tags:

rust

lifetime

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:

  • adding MissingParamError::new which will pre-render full description
  • adding an Option<String> which would render the description on demand and keep it around
like image 418
viraptor Avatar asked May 24 '15 08:05

viraptor


1 Answers

No; 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).

like image 134
DK. Avatar answered Oct 30 '22 01:10

DK.