I'll keep the story short so please don't comment with "why would you ever need something like this". I working with an encoder that encodes a type (e.g. T
), vector of a type (e.g. Vec<T>
), optional type (e.g. Option<T>
), and optional vector of a type (e.g. Option<Vec<T>>
). Each of the formats is encoded in a completely different way. The create I'm building provides the engine and users can define types T
. Each T
must implement a certain trait X
.
I've built a "perfect" solution where a user adds 4 implementations:
use modulex::{InputBuffer, Input, Buffer, X};
// EXAMPLE 1
struct CustomType {}
impl InputBuffer<CustomType> for Input {} // OK
impl InputBuffer<Option<CustomType>> for Input {} // rustc E0117
impl InputBuffer<Vec<CustomType>> for Input {} // rustc E0117
impl InputBuffer<Option<Vec<CustomType>>> for Input {} // rustc E0117
// EXAMPLE 2
struct CustomType {}
impl From<CustomType> for Buffer {} // OK
impl From<Option<CustomType>> for Buffer {} // rustc E0117
impl From<Vec<CustomType>> for Buffer {} // rustc E0117
impl From<Option<Vec<CustomType>>> for Buffer {} // rustc E0117
Note that the Buffer
, Input
and InputBuffer
are structures from the crate and CustomType
is a structure defined by the user. The naming above is not important. I'd just like to show you how the concept works. Well, actually it does not. Rust complains with E0117
on Vec
and Option
type implementation.
Can this be solved?
Alternatively, is it possible to create an enum
like below where T
is the user's custom type:
enum Buffer<T: impl X> {
Value(T),
Option(Option<T>),
Vec(Vec<T>),
VecOption(Option<Vec<T>>),
}
So the summary, a certain function must accept these 4 formats of a custom user-defined type that implements X
, where X and the function are provided by the crate.