Struct 实现内部类型';外型的特征
对于结构:Struct 实现内部类型';外型的特征,struct,rust,traits,Struct,Rust,Traits,对于结构: 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]时,一切都很好
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]
时,一切都很好
的什么特性导致索引错误[u8;5]
- 如何为
实现它U85
x[y]
语法。切片索引的一个缺点是x
,x..y
,,.y
,x..
都是不同的类型。您可以选择要支持的内容,但如果您只想做切片可以做的事情,可以这样实现:
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]
}
}
你在寻找这种特质吗?@kmdreko谢谢,是的,就是这样。如果你写下来作为答复,我会接受的。
use derive_more::Index;
#[derive(Index)]
struct U85([u8; 5]);