Generics 使此函数成为泛型函数时,如何满足特征边界?

Generics 使此函数成为泛型函数时,如何满足特征边界?,generics,rust,traits,Generics,Rust,Traits,通过学习Rust(我来自Javascript/Python背景),我一直在使用image rs(0.23.12)库来实现一些基本的图像分析函数。我通过ImageRS为此提供的迭代器访问像素数据。下面是一个函数的最小示例,该函数接受对图像子区域(image::SubImage)的引用,并遍历其中的像素,对每个像素进行比较 (游乐场) 这将从编译器中得出以下结论: binary operation `!=` cannot be applied to type `<I as GenericIma

通过学习Rust(我来自Javascript/Python背景),我一直在使用image rs(0.23.12)库来实现一些基本的图像分析函数。我通过ImageRS为此提供的迭代器访问像素数据。下面是一个函数的最小示例,该函数接受对图像子区域(
image::SubImage
)的引用,并遍历其中的像素,对每个像素进行比较

(游乐场)

这将从编译器中得出以下结论:

binary operation `!=` cannot be applied to type `<I as GenericImageView>::Pixel`
the trait `std::cmp::PartialEq` is not implemented for `<I as GenericImageView>::Pixel` rustc(E0369)
然后,它抱怨闭包中的“像素”和“白色”的类型不匹配:

mismatched types
expected associated type `<I as GenericImageView>::Pixel`
            found struct `Luma<u8>`
consider constraining the associated type `<I as GenericImageView>::Pixel` to `Luma<u8>`
for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html rustc(E0308)
在这一点上,我试着用不同的方式诠释“像素”和“白色”,但我认为自己被难住了。你知道,我也知道,Luma实现了比较
pixel!=白色
,但我不知道如何说服rustc


(如果有帮助的话,函数可以只处理类型为
Luma,Vec
ImageBuffers
——我只需要处理单色图像。但它确实需要处理任何(不可变的)图像视图。)

编译器关于“约束关联类型
::关联的
具体的
”的建议这意味着您需要为trait绑定中的关联类型直接请求一个具体类型。这是通过
Trait
语法完成的-例如,要将
I
约束到生成字符串的迭代器,您需要编写
I:iterator
。在
find_dark_pixels
的情况下,您将请求
Pixel
关联类型为
Luma
,如下所示:

fn find_dark_pixels<I: GenericImageView<Pixel = Luma<u8>>>(img: &I) {
fn查找暗像素(img:&I){

欢迎来到Stack Overflow!很难回答您的问题,因为它不包含一个。我们无法说出是什么板条箱(及其版本),类型、特征、字段等都存在于代码中。如果您试图在上重现错误,我们将更容易为您提供帮助。如果可能,否则在全新的货运项目中,则您的问题将包括其他信息。您可以使用这些信息来减少您在此处发布的原始代码。谢谢!请回答您的问题并粘贴您得到的准确完整的错误-这将帮助我们了解问题所在,以便我们能够提供最好的帮助。有时试图解释错误消息是很棘手的,而且它实际上是错误消息的另一部分,这一点很重要。请使用直接运行编译器的消息,而不是由编译器生成的消息n IDE,它可能正试图为您解释错误。我相信编译器关于“约束关联类型”的建议希望您执行
fn查找暗像素(img:&I)
。这就解决了问题,谢谢!
fn find_dark_pixels<I: GenericImageView>(img: &I)
    where <I as GenericImageView>::Pixel: std::cmp::PartialEq
(the rest is unchanged)
mismatched types
expected associated type `<I as GenericImageView>::Pixel`
            found struct `Luma<u8>`
consider constraining the associated type `<I as GenericImageView>::Pixel` to `Luma<u8>`
for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html rustc(E0308)
fn find_dark_pixels<I: GenericImageView>(img: &I)
    where <I as GenericImageView>::Pixel: Luma<u8>
(the rest is unchanged)
expected trait, found struct `Luma`
not a trait rustc(E0404)
fn find_dark_pixels<I: GenericImageView<Pixel = Luma<u8>>>(img: &I) {