Type Alias for Readability with Associated Traits

Suppose I have something with generics and a trait with associated types like this:

pub struct MyAwesumType<A, B> {
    _value_of_type_a: A,
    _value_of_type_b: B,
}

pub trait MyTrait {
    type SomeDescriptionOfWhatAIsFor;
    type SomeDescriptionOfWhatBIsFor;
    type Error;

    fn get_the_thing(
        &self,
    ) -> std::result::Result<
        MyAwesumType<Self::SomeDescriptionOfWhatAIsFor, Self::SomeDescriptionOfWhatBIsFor>,
        Self::Error,
    >;
}

What I want to do is alias the "specialization" in that return type to make it less burdensome to read when grokking the trait. For example I'd like to do this, which is not valid:

pub struct MyAwesumType<A, B> {
    _value_of_type_a: A,
    _value_of_type_b: B,
}

pub trait MyTrait {
    type SomeDescriptionOfWhatAIsFor;
    type SomeDescriptionOfWhatBIsFor;
    type Error;

    use MyAwesumType as MyAwesumType<Self::SomeDescriptionOfWhatAIsFor, Self::SomeDescriptionOfWhatBIsFor>;
    use Result<T> as std::result::Result<T, Self::Error>

    fn get_the_thing(&self) -> Result<MyAwesumType>;
}

fn main() {
    println!("Hello, world!");
}

Or maybe like this, also invalid:

pub struct MyAwesumType<A, B> {
    _value_of_type_a: A,
    _value_of_type_b: B,
}

pub trait MyTrait {
    type SomeDescriptionOfWhatAIsFor;
    type SomeDescriptionOfWhatBIsFor;
    type Error;

    type MyAwesumType =
        MyAwesumType<Self::SomeDescriptionOfWhatAIsFor, Self::SomeDescriptionOfWhatBIsFor>;
    type Result<T> = std::result::Result<T, Self::Error>;

    fn get_the_thing(&self) -> Self::Result<Self::MyAwesumType>;
}

Is there any way to do some, if not all, of the type aliasing that I would like to do in the trait definition?

You can define a type alias which uses the trait's associated types, given the implementing type:

type TrAwesum<T> = MyAwesumType<
    <T as MyTrait>::SomeDescriptionOfWhatAIsFor,
    <T as MyTrait>::SomeDescriptionOfWhatBIsFor,
>;

Then, you can use this type in trait method signatures and elsewhere by specifying only the implementing type:

fn get_the_thing(&self) -> std::result::Result<TrAwesum<Self>, Self::Error>;

You can't (currently) make the type alias can be associated with the type itself, but that's just a matter of what namespace it's in — it will still work for shortening the long type name.

2 Likes

Thank you @kpreid, that helps!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.