Guest User

Untitled

a guest
Nov 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. #![feature(try_from)]
  2.  
  3. use std::convert::TryInto;
  4.  
  5. struct Foo {
  6. s: String,
  7. }
  8.  
  9. impl Foo {
  10. fn to_bar<'foo>(&'foo self) -> Option<Bar<'foo>> {
  11. Some(Bar { s: &self.s[1..] })
  12. }
  13. }
  14.  
  15.  
  16. impl<'foo> TryInto<Baz<'foo>> for &'foo Foo {
  17. type Error = ();
  18.  
  19. fn try_into(self) -> Result<Baz<'foo>, ()> {
  20. if let Some(bar) = self.to_bar() {
  21. (&bar).try_into()
  22. } else {
  23. Err(())
  24. }
  25. }
  26. }
  27.  
  28.  
  29. struct Bar<'foo> {
  30. s: &'foo str,
  31. }
  32.  
  33. impl<'a, 'foo> TryInto<Baz<'foo>> for &'a Bar<'foo> {
  34. type Error = ();
  35.  
  36. fn try_into(self) -> Result<Baz<'foo>, ()> {
  37. if self.s.ends_with("!") {
  38. Ok(Baz { s: &self.s[1..] })
  39. } else {
  40. Err(())
  41. }
  42.  
  43. }
  44. }
  45.  
  46. #[derive(Debug)]
  47. struct Baz<'foo> {
  48. s: &'foo str,
  49. }
  50.  
  51. fn main() {
  52. let f = Foo { s: "Foo!".into() };
  53. let b: Result<Baz, ()> = (&f).try_into();
  54. println!("{:?}", b);
  55. }
Add Comment
Please, Sign In to add comment