Define type alias for trait with generics

I try to define alias for BlockMode, so I can use it as function argument, but it error out, pls advise

fn encrypt(cipher: impl BlockMode<C: BlockCipher + BlockEncrypt + BlockDecrypt, P: Padding>) {
// ...

the function below works, but it's not for trait but struct

fn encrypt<C: BlockCipher + BlockEncrypt + BlockDecrypt, P: Padding>(cipher: &Cbc<C, P>) { //... }

What you want is nested impl Trait. Unfortunately, nested impl Trait is not allowed:

trait Trait<T> {}

fn a(f: impl Trait<impl std::fmt::Display>) {}
error[E0666]: nested `impl Trait` is not allowed
 --> src/
3 | fn f(a: impl Trait<impl std::fmt::Display>) {}
  |         -----------^^^^^^^^^^^^^^^^^^^^^^-
  |         |          |
  |         |          nested `impl Trait` here
  |         outer `impl Trait`


You need at least some full generics to achieve that:

fn f<T: std::fmt::Display>(a: impl Trait<T>) {}

Of course you can always use only generics:

fn f<T: std::fmt::Display, U: Trait<T>>(a: U) {}
1 Like