Search code examples
dynamicrustboxassociated-types

How can the value of the associated types must be specified for a Box<dyn Trait> field?


I'd like to create a boxed struct field for a trait where the trait has an associated type. Here's an example using digest::Digest:

use digest::Digest;
struct Crypto {
    digest: Box<dyn Digest>,
}

This fails to compile with the error:

the value of the associated type OutputSize (from trait digest::Digest) must be specified

Sometimes I may want to use a sha2::Sha256 and other times a sha2::Sha512, each with a different OutputSize. Is it possible to create a boxed struct field with a dynamic associated type? And if so, how?


Solution

  • You could make your own trait and give it a blanket impl across all Digest instances that returns Box<[u8]> or Vec<u8> instead of GenericArray, but you don't need to as the authors of digest have already created a DynDigest trait for you:

    use digest::DynDigest;
    
    struct Crypto {
        digest: Box<dyn DynDigest>,
    }