Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

dynamic - 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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...