Aliasing Traits

2015/07/26 10:10am

(2020-04-04) Trait alias was finally introduced in the RFC 1733.

Rust‘s traits and its bound syntax gets longer and longer as you add associated types or specify multiple trait bounds with the + syntax.

struct A<T: Iterator<Item=char>> {
    ...
}

On the other hand, ordinaly types can be aliased with type keyword, however it can not be used for traits.

type CharIterator = Iterator<Item=char>;

// ERROR: note: `type` aliases cannot be used for traits
struct A<T: CharIterator> {
    ...
}

In the past, there was the proposal and discussion about trait alias:

Allow type to create an alias for several trait bounds · Issue #8634 · rust-lang/rust

I don’t see a compelling need for this, since you can just declare another empty trait that inherits from both. I realize it’s somewhat more concise if you have the additional syntax, but it just doesn’t seem to add enough value to justify adding a new feature. Closing.

It is true, I can get similar effect by declaring an empty trait which inherits another trait:

trait CharIterator: Iterator<Item=char> {}

struct A<T: CharIterator> {
    ...
}

However, the type that implements the existing Iterator<Item=char> (such as (std::str::Chars) can not be used for an implementation for T because it does not implement the CharIterator.

Let’s write impl which states “A type that implements Iterator<Item=char> also implements CharIterator.

trait CharIterator: Iterator<Item=char> {}
impl<T: Iterator<Item=char>> CharIterator for T {}

struct A<T: CharIterator> {
    it: T,
}

...

let a = A { it: "test".chars() };

References: