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 traitdigest::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?
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>,
}