【问题标题】:Implementing inner type's traits on outer type在外部类型上实现内部类型的特征
【发布时间】:2021-04-18 07:12:33
【问题描述】:

使用结构:

    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 实现它?

【问题讨论】:

  • 你在寻找 Index 特征吗?
  • @kmdreko 谢谢,是的,就是这样。如果你把它写成答案,我会接受它。

标签: struct rust traits


【解决方案1】:

x[y] 语法是通过 IndexIndexMut 特征实现的。切片索引的一个问题是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]);

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2019-12-08
    • 1970-01-01
    • 2013-04-26
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多