dimanche 3 novembre 2019

Construct generic Struct from a Trait function in Rust

I want to write a trait that allows me to construct new structs of the implementing type, but with different type parameters. For example, say I hav some struct

struct Generic<T> {
    t: T,
}

and I want a trait Constructable that lets me call Generic::new_from_q::<Q>(q as Q), i.e. my trait would look like this (in pseudo-rust):

trait Constructable {
    fn new_from_q<Q>(q: Q) -> Self<Q>; // Self<Q> would be e.g. Generic<Q>
}

impl<T> Constructable for Generic<T> {
    type T = T;
    fn new_from_q<Q>(q: Q) -> Generic<Q> {
        Generic { t: q }
    }
}

Of course this makes no sense since the trait cannot guarantee that Self will be able to take the type parameter Q. The closest I have come to implementing the desired constructor behaviour is this:

trait Constructable {
    type T;
    fn new_from_q<Q>(q: Q) -> impl Constructable<T = Q>; // currently invalid
}

(playground link) which is currently not possible due to the limitations of the impl Trait syntax (see #34511), which is (I think)

  • not allowed in traits
  • not able to take values for associated types

So, how do I work around these limitations? Is there some common programming pattern to allow me to do this (I would like to avoid dynamic trait objects)?

Aucun commentaire:

Enregistrer un commentaire