我想创建一个我可以使用的数据库结构,如下所示:
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`?
我显然可以使E
明确如下:
struct DatabaseUgly<S, E>
where
S: Storage<E>,
E: Element
但是我必须重复元素类型:
let c: DatabaseUgly<Disk<u8>, u8> = ...
我如何让Database
工作?
注意:由于它不止一次发生,请不要先编辑我的问题标题。我可能没有使用正确的术语,但如果我知道究竟要找什么,我可能不会这样询问/搜索。
一个简单的解决方案是在特征中使用关联类型,而不是通用:
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)