enums - How to extend the lifetimes of Strings within functions of traits that require returning &str? -


problem


i trying implement std::error::error trait on enum. elements of enum enum variants, , generate different error message containing data variant. implementation below formatted string deref &str don't live long enough.

the general solution return string. however, not option here returned type must &str specified error trait.


example: playground link


it important note variants may not contain usize, , might instead enum, or struct etc.

use std::fmt; use std::fmt::{display, formatter}; use std::error;  #[derive(debug)] enum enumerror {     a,     b(usize),     c(usize),     d, }  impl error::error enumerror {     fn description(&self) -> &str {         use enumerror::*;         match *self {             => "a happened",             b(value) => &*format!("b happened info: {:?}", value),             c(value) => &*format!("b happened info: {:?}", value),             d => "d happened",         }     } }  impl display enumerror {     fn fmt(&self, f: &mut formatter) -> fmt::result {     use std::error::error;         write!(f, "{}", self.description())     } }  fn main() {} 

the string create needs owned something. when create local string in method, have transfer ownership caller. since have return &str, not option.

the way around store string in struct itself. can declare enum value b(usize, string), put description there when create it, , return with

b(_, ref descr) => descr 

to frank, description not supposed terribly detailed message, needs give general description of kind of error is, why returns &str. didn't see instances of writing dynamic data description in standard library, it's static string. display implementation different matter though, in there can more verbose.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -