Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>>,
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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),
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading