Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/65875468/how-can-the-value-of-the-associated-types-must-be-specified-for-a-boxdyn-trait

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...