编者注:这个问题是在 Rust 1.0 之前提出的,并且使用了不再有效的语法。另外,这个问题中的具体问题在 Rust 1.0 中不再出现。
有一个结构包含唯一的字段,一个固定宽度的字节数组。有人会认为从std::cmp
for 实现特征很简单,但推导不起作用:
#[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
文档建议 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 参考手册中的这一行可以解释它:
产生确定大小向量的表达式不能在期望大小不定向量的上下文中进行评估;必须将确定大小的向量内容复制到一个不定大小的不同向量中。
动机尚不清楚,但我想这与存储长度有关。
无论如何,是否可以使用 for 的实现来比较两个固定长度的数组&[]
,而无需复制?