0

I want to create a database structure that I can use like this:

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

However, when I naively implement it:

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,
}

I get an error that E is unknown:

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

I could obviously make E explicit such as:

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

But then I would have to repeat the element type:

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

How can I make Database work?


Note: Since it happened more than once, please do not edit the title of my question without discussing it first. I might not be using the right terminology, but if I knew what exactly to look for I would probably not be asking / searching this way.

left4bread
  • 1,514
  • 2
  • 15
  • 25

1 Answers1

3

A simple solution is to use associated type in the trait, rather than a generic:

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,
}

(link to playground)

See also When is it appropriate to use an associated type versus a generic type?

mcarton
  • 27,633
  • 5
  • 85
  • 95