Advertisement
Guest User

Untitled

a guest
May 21st, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct InnerError;
  3.  
  4. #[derive(Debug)]
  5. struct Error<T, U> {
  6. value1: T,
  7. value2: U,
  8. inner: InnerError,
  9. }
  10.  
  11. #[derive(Debug)]
  12. struct ContextSelector<T0, U0> {
  13. value1: T0,
  14. value2: U0,
  15. }
  16.  
  17. // Ideally, this would just be `trait IntoError`, but that causes
  18. // "the type parameter `T` is not constrained", etc. This generic
  19. // parameter allows us to "bundle" a bunch of other generics when
  20. // we implement the trait.
  21. trait IntoError<T> {
  22. type From;
  23. type Error;
  24.  
  25. fn into_error(self, inner: Self::From) -> Self::Error;
  26. }
  27.  
  28. impl<T, U, T0, U0> IntoError<(T, U)> for ContextSelector<T0, U0>
  29. where
  30. T0: Into<T>,
  31. U0: Into<U>,
  32. {
  33. type From = InnerError;
  34. type Error = Error<T, U>;
  35.  
  36. fn into_error(self, inner: Self::From) -> Self::Error {
  37. let ContextSelector { value1, value2 } = self;
  38.  
  39. let value1 = value1.into();
  40. let value2 = value2.into();
  41.  
  42. Error {
  43. value1,
  44. value2,
  45. inner,
  46. }
  47. }
  48. }
  49.  
  50. fn example_i32() -> Error<i32, i32> {
  51. ContextSelector {
  52. value1: 1,
  53. value2: 2,
  54. }
  55. .into_error(InnerError)
  56. }
  57.  
  58. fn example_string() -> Error<String, String> {
  59. ContextSelector {
  60. value1: "1",
  61. value2: "2",
  62. }
  63. .into_error(InnerError)
  64. }
  65.  
  66. fn main() {
  67. let a = example_i32();
  68. let b = example_string();
  69.  
  70. println!("{:?}", a);
  71. println!("{:?}", b);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement