在外部类型上实现内部类型的特征

Implementing inner type's traits on outer type

结构:

    struct U85 (
        [u8; 5]
    );

我收到错误:

error[E0608]: cannot index into a value of type `&U85`
   --> /home/fadedbee/test.rs:11:40
    |
11  |                     s.serialize_bytes(&self[..])
    |

而当我使用简单类型时 [u8; 5] 一切都很好。

x[y] 语法是用 Index and IndexMut 特性实现的。切片索引的一个问题是 xx..y....yx.. 都是不同的类型。你可以选择你想要支持的东西,但如果你只想做切片可以做的事情,你可以像这样实现它:

use std::ops::Index;
use std::slice::SliceIndex;

struct U85([u8; 5]);

impl<I> Index<I> for U85 where I: SliceIndex<[u8]> {
    type Output = I::Output;
    fn index(&self, index: I) -> &I::Output {
        &self.0[index]
    }
}

如果您发现自己经常为包装器类型实现特征,您可以考虑使用 derive_more 板条箱,这将允许您派生出遵循内部特征的特征(如 Index)类型。

use derive_more::Index;

#[derive(Index)]
struct U85([u8; 5]);