比较定长数组

Mic*_*vko 4 arrays rust rust-obsolete

编者注:这个问题是在 Rust 1.0 之前提出的,并且使用了不再有效的语法。此外,这个问题中的具体问题在 Rust 1.0 中不再出现。

有一个结构体包含唯一的字段,一个固定宽度的字节数组。有人会认为从std::cmpfor实现特征很简单,但派生不起作用:

#[deriving(Eq)]
pub struct ID {
    bytes: [u8, ..::constants::ID_SIZE]
}

src/id.rs:3:5: 3:40 error: mismatched types: expected `&&[u8]` but found `&[u8, .. 20]` ([] storage differs: expected `&` but found `20`)
src/id.rs:3     bytes: [u8, ..::constants::ID_SIZE]
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in expansion of #[deriving]
src/id.rs:1:1: 2:4 note: expansion site
Run Code Online (Sandbox Code Playgroud)

文档表明,等式为实现&[]~[],而不是固定的宽度阵列。手动强制&[]也不起作用:

impl Eq for ID {
    fn eq(&self, other: &ID) -> bool {
        (&self.bytes).eq(&other.bytes)
    }
}

src/id.rs:7:26: 7:38 error: mismatched types: expected `&&[u8, .. 20]` but found `&[u8, .. 20]` (expected &-ptr but found vector)
src/id.rs:7         (&self.bytes).eq(&other.bytes)
                                     ^~~~~~~~~~~~
src/id.rs:7:9: 7:39 error: failed to find an implementation of trait std::cmp::Eq for [u8, .. 20]
src/id.rs:7         (&self.bytes).eq(&other.bytes)
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

Rust 参考手册中的这一行可以解释它:

生成大小确定的向量的表达式不能在期望大小不定的向量的上下文中进行评估;必须将确定大小的向量内容复制到一个大小不定的不同向量中。

动机尚不清楚,但我想这与存储长度有关。

无论如何,是否可以使用 for 的实现来比较两个固定长度的数组&[],而无需复制?

A.B*_*.B. 6

文档表明 Eq 是为 &[] 和 ~[] 实现的,而不是为固定宽度的数组实现的。

是的,这是因为 [T,..2] 与 [T,..3] 是不同的类型。

无论如何,是否可以使用 &[] 的实现来比较两个固定长度的数组,而无需复制?

容易地

impl Eq for ID {
    fn eq(&self, other: &ID) -> bool {
        self.bytes.iter().zip(other.bytes.iter()).all(|(a,b)| a == b) 
    }
}
Run Code Online (Sandbox Code Playgroud)