数组上的 PartialEq

luk*_*uke 4 arrays rust deriving

关于 Rust 数组的问题(恒定大小的数组,[T,..Size])。我正在努力做好以下工作:

#[deriving(PartialEq)]
struct Test {
  dats : [f32, ..16]
}
Run Code Online (Sandbox Code Playgroud)

我知道我不能使用派生并简单地编写自己的 PartialEq,但这相当令人讨厌......给出的错误消息对我来说也很神秘(见下文)。有没有适当的乡村方式来做到这一点?

rustc ar.rs 
ar.rs:4:3: 4:20 error: mismatched types: expected `&&[f32]` but found `&[f32, .. 16]` (expected &-ptr but found vector)
ar.rs:4   dat : [f32, ..16]
          ^~~~~~~~~~~~~~~~~
note: in expansion of #[deriving]
ar.rs:2:1: 3:7 note: expansion site
ar.rs:4:3: 4:20 error: mismatched types: expected `&&[f32]` but found `&[f32, .. 16]` (expected &-ptr but found vector)
ar.rs:4   dat : [f32, ..16]
          ^~~~~~~~~~~~~~~~~
note: in expansion of #[deriving]
ar.rs:2:1: 3:7 note: expansion site
error: aborting due to 2 previous error
Run Code Online (Sandbox Code Playgroud)

从今天开始我就开始了 Rust 夜间构建。

谢谢!

huo*_*uon 5

这是一个错误:#7622 “固定长度数组没有实现特征”。正如 AB 所说,没有办法参数化固定长度数组的长度,因此实现特征的唯一方法就是实际将它们写出来:

impl PartialEq for [f32, .. 0] { ... }

impl PartialEq for [f32, .. 1] { ... }

impl PartialEq for [f32, .. 2] { ... }

impl PartialEq for [f32, .. 3] { ... }

// ...
Run Code Online (Sandbox Code Playgroud)

(当然,这可以通过宏来完成:但是为所有可能的特征实现所有可能的长度仍然是不可行的。)

您需要自己实现这些特征deriving,例如

struct Test { dats: [f32, .. 16] }

impl PartialEq for Test {
    fn eq(&self, other: &Test) -> bool {
        self.dats == other.dats
    }
}

fn main() {
    let a = Test { dats: [0.0, .. 16 ]};
    let b = Test { dats: [100.0, .. 16 ]};

    println!("{}", a == b);
}
Run Code Online (Sandbox Code Playgroud)

您可能会认为很奇怪,您可以在不实现它的情况下使用==with (这就是大多数类型的重载方式,如上面所示):它的工作原理是因为编译器对如何使用固定长度向量有内置的理解,因此可以直接使用它没有触及特质。[f32, .. 16]PartialEq==Test==