Trait enforced deconstruction

Is it possible to have "trait enforced deconstruction" ?

What I mean be deconstruction here is for a type that's "constructed" from one or more underlaying subtypes as the owner to "return them back".

For example:

struct HasTwo<ONE, TWO> {
  one: ONE,
  two: TWO,

impl<ONE, TWO> HasTwo<ONE, TWO> {
  pub fn deconstruct(self) -> (ONE, TWO) {
    (, self.two)

Is it possible to enforce this somehow via a trait however, given that your implementors might have multiple components to "return back"?

Well, since you, as the trait creator aren't allowed to know what exactly the implementing struct contains, you can't just say "Give me whatever Self contains".

If that is okay, you can let the implementor choose the type using an associated type:

trait Deconstruct<'a> {
    type Result: 'a;
    fn deconstruct(self) -> Self::Result;

But I get the hint you want something like variadics:

trait Deconstruct<T...> {
    fn deconstruct(self) -> (T...);

But this isn't supported in Rust.

This is a pretty loose comment, but your question reminds me of frunk's Generic, which is a trait for deconstructing and reconstructing values based on what they contain.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.