编者注:在Rust 1.0之前询问了这个问题并使用了不再有效的语法 . 此外,Rust 1.0中不再出现此问题中的特定问题 .
有一个结构包含唯一的字段,一个固定宽度的字节数组 . 有人会认为从 std::cmp
实现特征是直截了当的,但派生不起作用:
#[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
documentation表明Eq是针对 &[]
和 ~[]
实现的,而不是针对固定宽度数组 . 手动强制到 &[]
也不起作用:
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)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rust参考手册中的这一行可以解释它:
产生一定大小的载体的表达不能在期望无限大小的向量的上下文中进行评估;必须将确定大小的矢量内容复制到不确定大小的不同矢量中 .
动机尚不清楚,但我想这与存储长度有关 .
无论如何,是否可以使用 &[]
的实现比较两个固定长度数组,而无需复制?
1 回答
是的,那是因为[T,.. 2]与[T,.. 3]的类型不同 .
容易