to_trait/lib.rs
1use std::convert::TryInto;
2
3/// Provides methods similar to `.into()` and `.try_into()`,
4/// except they take type arguments. See each method's documentation
5/// for details.
6///
7pub trait To {
8 /// A version of `std::convert::Into::into` that lets you provide
9 /// type arguments to the method call.
10 ///
11 /// ```
12 /// use to_trait::To;
13 /// assert_eq!(5i32, 5u8.to::<i32>());
14 /// ```
15 fn to<T>(self) -> T
16 where
17 Self: Into<T>,
18 {
19 self.into()
20 }
21
22 /// a version of `std::convert::TryInto::try_into` that lets you provide type arguments
23 /// to the method call.
24 ///
25 /// ```
26 /// use to_trait::To;
27 /// assert_eq!(255u32.try_to::<u8>(), Ok(255u8));
28 /// assert!(256u32.try_to::<u8>().is_err());
29 /// ```
30 fn try_to<T>(self) -> Result<T, <Self as TryInto<T>>::Error>
31 where
32 Self: TryInto<T>,
33 {
34 self.try_into()
35 }
36}
37
38impl<T> To for T {}
39
40#[test]
41fn test_it() {
42 assert_eq!(42u32.to::<u64>(), 42u64);
43 assert_eq!(42u32.try_to::<u8>(), Ok(42u8));
44 assert!(500.try_to::<u8>().is_err());
45}