Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. use std::fmt::Display;
  2. use std::fmt::Formatter;
  3. use std::fmt::Error;
  4. use std::ops::Deref;
  5. use std::ops::DerefMut;
  6.  
  7. struct MyResult<T, E>(Result<T, E>);
  8.  
  9. impl<T: Display, E: Display> Display for MyResult<T, E> {
  10. fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
  11. match self.0 {
  12. Ok(ref v) => write!(f, "Ok({})", v),
  13. Err(ref v) => write!(f, "Err({})", v),
  14. }
  15. }
  16. }
  17.  
  18. ///////////////// This is not mandatory
  19.  
  20. impl<T, U> Deref for MyResult<T, U> {
  21. type Target = Result<T, U>;
  22.  
  23. fn deref(&self) -> &Result<T, U> {
  24. &self.0
  25. }
  26. }
  27.  
  28. impl<T, U> DerefMut for MyResult<T, U> {
  29. fn deref_mut(&mut self) -> &mut Result<T, U> {
  30. &mut self.0
  31. }
  32. }
  33.  
  34. //////////////////
  35.  
  36. fn main() {
  37. let result: Result<u32, String> = Result::Ok(50);
  38. println!("{:?}", result);
  39. let my_result = MyResult(result);
  40. println!("{}", my_result);
  41. // If you implement Deref, you can keep using Result methods
  42. if my_result.is_ok() {
  43. println!("All good");
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement