#arguments #traits #try-into #call

to_trait

A trait with methods similar to .into() and .try_into(), except they take type arguments

2 releases

0.1.1 Apr 2, 2020
0.1.0 Apr 2, 2020

#1987 in Rust patterns

Download history 200/week @ 2023-12-18 29/week @ 2023-12-25 223/week @ 2024-01-01 205/week @ 2024-01-08 146/week @ 2024-01-15 169/week @ 2024-01-22 166/week @ 2024-01-29 112/week @ 2024-02-05 97/week @ 2024-02-12 142/week @ 2024-02-19 243/week @ 2024-02-26 329/week @ 2024-03-04 169/week @ 2024-03-11 308/week @ 2024-03-18 181/week @ 2024-03-25 436/week @ 2024-04-01

1,099 downloads per month

MIT license

4KB

to_trait

Provides the To trait, which provides methods similar to .into() and .try_into(), except they take type arguments. The trait looks like this:

trait To {
    fn to<T>(self) -> T where Self: Into<T>;
    fn try_to<T>(self) -> Result<T, Self::Error> where Self: TryInto<T>;
}

and you use it like this:

use to_trait::To;
let five_u64 = 5u32.to::<u64>();
let five_u8 = 5u32.to::<u8>().unwrap();

At first glance, this might not seem very useful, but sometimes the compiler can't infer the output type of a call to .into(). This happens a lot with method chains, e.g. if you call .into().some_other_method(), and it can be pretty annoying.

What woud be ideal is if we could write the desired output type as type arguments to the method. Unfortunately, because Into<T> takes T as a trait type parameter, we can't supply it when calling the method - the only way to supply the type arguments is by falling back to universal function call syntax, with Into::<T>::into(..).

The methods on To trait essentially act as type inference helpers, letting you supply the type arguments while still using method call syntax. As a bonus, they are shorter by two characters 😄

License

MIT

No runtime deps