如何在泛型/嵌套结构中省略顶级类型参数?

问题描述 投票:0回答:1

我想创建一个我可以使用的数据库结构,如下所示:

let c: Database<Disk<u8>> = ...

但是,当我天真地实现它:

trait Element {}

trait Storage<E> where E: Element {}

struct Disk<E> where E: Element {
    data: E,
}  

impl<E> Storage<E> for Disk<E> where E: Element {}

struct Database<S>
where
    S: Storage<E>, 
    E: Element,
{
    storage: S,
}

我得到一个E未知的错误:

error[E0412]: cannot find type `E` in this scope
  --> src/main.rs:30:16
   |
30 |     S: Storage<E>, // <-- Error: E not found.
   |                ^ did you mean `Eq`?

Playground

我显然可以使E明确如下:

struct DatabaseUgly<S, E>
where
    S: Storage<E>,
    E: Element 

但是我必须重复元素类型:

let c: DatabaseUgly<Disk<u8>, u8> = ...

我如何让Database工作?


注意:由于它不止一次发生,请不要先编辑我的问题标题。我可能没有使用正确的术语,但如果我知道究竟要找什么,我可能不会这样询问/搜索。

rust
1个回答
3
投票

一个简单的解决方案是在特征中使用关联类型,而不是通用:

trait Element {}

trait Storage { // not generic
    type Element: Element;
}

struct Disk<E>
where
    E: Element,
{
    data: E,
}

impl<E> Storage for Disk<E>
where
    E: Element,
{
    type Element = E;
}

struct Database<S>
where
    S: Storage,
    S::Element: Element,
{
    storage: S,
}

(Qazxswpoi)

另见link to playground

© www.soinside.com 2019 - 2024. All rights reserved.