How to use sized traits in structs?

I’m trying to use the AES crate, which offers three algorithms: AES128, AES192 and AES256. I’m trying to create a struct that can create the correct algorithm by detecting the key size, and save it to later use.

I see they all implement the BlockEncrypt (I only need encryption) trait, but when I try to make a field in the struct with this type, even when supplying the size, i get an "the trait BlockEncrypt cannot be made into an object. the trait cannot be made into an object because it requires Self: Sized " error.

pub struct MyStruct<'a, T: Sized> {
       ciph: Box< dyn BlockEncrypt<BlockSize = T>>,
}

>Solution :

As @cdhowie mentioned, you can’t create a trait object from a trait with a Sized bound. Instead, you can create an enum:

enum MyAlgorithm {
    AES128(AES128),
    AES192(AES192),
    AES256(AES256),
}

Leave a Reply