如何必须为 Box<dyn Trait> 字段指定关联类型的值?

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

我想为特征创建一个盒装结构字段,其中特征具有关联类型。这是一个使用 digest::Digest:

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

编译失败并出现错误:

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

有时我可能想使用 sha2::Sha256,有时我想使用 sha2::Sha512,每个都有不同的 OutputSize。是否可以创建具有动态关联类型的盒装结构字段?如果是,怎么做?

您可以创建自己的特征,并在 returns Box<[u8]>Vec<u8> 而不是 GenericArray 的所有 Digest 实例中对其进行全面实施,但您不需要,因为 digest 的作者已经为您创建了一个 DynDigest 特征:

use digest::DynDigest;

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