is trying to say that we are using Add on the type D::OutputSize but not requiring it as a constraint, which we can do like so:fn compute_hash<D: Digest>(input_data: &str) -> String where D::OutputSize: std::ops::Add如果进行此更改,则会出现下一个错误:If you make this change, you'll come to the next error: | ^^^^^^ the trait `digest::generic_array::ArrayLength<u8>` is not implemented for `<<D as sha2::Digest>::OutputSize as std::ops::Add>::Output`所以还有另一个要求,但是我们也可以添加它:so there is another requirement, but we can add that too:fn compute_hash<D: Digest>(input_data: &str) -> String where D::OutputSize: std::ops::Add, <D::OutputSize as std::ops::Add>::Output: digest::generic_array::ArrayLength<u8>这将编译.但是让我们深入探讨为什么需要这些约束的原因. 完成 返回 Output< D> ,我们知道它是 GenericArray< u8,< D as Digest> :: OutputSize> .显然, format!("{:x}",...)需要特征 LowerHex ,因此我们可以看到此类型何时满足此特征.请参见:But let's dive into the reasons why these constraints are necessary. finalize returns Output<D> and we know that it is the type GenericArray<u8, <D as Digest>::OutputSize>. Evidently format!("{:x}", ...) requires the trait LowerHex so we can see when this type satisfies this trait. See:impl<T: ArrayLength<u8>> LowerHex for GenericArray<u8, T>where T: Add<T>, <T as Add<T>>::Output: ArrayLength<u8>, 那看起来很熟悉.因此,如果这些约束为true,则 finalize 的返回类型满足 LowerHex .That looks familiar. So the return type of finalize is satisfies LowerHex if these constraints are true.但是我们可以更直接地得到同一件事.我们希望能够使用 LowerHex 和我们可以这样说:But we can get at the same thing more directly. We want to be able to format using LowerHex and we can say that:fn compute_hash<D: Digest>(input_data: &str) -> String where digest::Output<D>: core::fmt::LowerHex因为这可以直接表达我们在泛型函数中使用的内容,所以这似乎是可取的.Since this can directly express what we use in the generic function, this seems preferable. 这篇关于泛型函数,用于计算哈希(digest :: Digest trait)并获取String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 15:53