9

Is it possible to create a trait alias with specified associated types? I'm using a method from similar question Type alias for multiple traits

trait Trait {
    type Item;
}

fn print<T>(value: T) where T: Trait<Item=char> {
}

trait Alias: Trait {}
impl<T: Trait<Item=char>> Alias for T {}

fn print_alias<T: Alias>(value: T) {
    print(value)
}

fn main() {
}

However it fails to compile with following error:

<anon>:12:5: 12:10 error: type mismatch resolving `<T as Trait>::Item == char`:
 expected associated type,
    found char [E0271]
<anon>:12     print(value)
              ^~~~~
<anon>:12:5: 12:10 note: required by `print`
<anon>:12     print(value)
              ^~~~~
error: aborting due to previous error

Playpen link: http://is.gd/LE4h6a

Community
  • 1
  • 1

3 Answers3

6

@Shepmaster's solution solves the problem locally; but you would have to specify the where T: Alias<Item=char> each time. Alternatively, you can solve it globally by requiring that all Alias implements Trait<Item=char>:

trait Alias: Trait<Item=char> {}
impl<T: Trait<Item=char>> Alias for T {}

Which of the global or local solutions is preferred is totally up to you.

mdup
  • 7,889
  • 3
  • 32
  • 34
  • Thanks for help. I got it now: `Trait` in `impl` means every `Trait` is `Alias`, but to make every `Alias` `Trait`, I need same constraint in trait declaration. – Mike Krasnenkov May 24 '15 at 13:53
3

You have currently only required that all values of Alias must implement Trait, but not that the type of Item must be char. To do that you have to use the following:

trait Alias: Trait<Item=char> {}
Snorre
  • 486
  • 3
  • 6
2

You still need to specify the associated type in your print_alias method:

fn print_alias<T>(value: T)
    where T: Alias<Item=char>
{
    print(value)
}

The problem is that you've specified that every Trait<Item=char> also implements Alias (and thus Alias<Item=char>), but that doesn't mean that every Alias implements Trait<Item=char>!

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366