Same struct twice, but with different impl

I have a struct that I want two different representations of. Specifically one has a Drop trait, and the other doesn't. Apart from the trivial way to do it:

struct InnerContext {
  a: u32,
  b: u32
}

struct Context {
  inner: InnerContext
}

impl Drop for Context {
  fn drop(&mut self) {
    // .. blah ..
  }
}

Are there any other ways to do it? (Read: Is there a different way I should be doing it to be more idiomatic?). Is this one of the use-cases for "newtypes"?

Depends on the details. Why do you need two? As for newtypes, the Context type in your current example is a newtype, and it is indeed a reasonable approach.

1 Like

It's related to a question you answered earlier. :slight_smile:

Essentially the issue is that I have a structure that is used in two different ways:

  • Passes data between threads
  • Is passed to the application to allow it to take certain actions, and return data to the original thread

The issue is that the application "must" take action with the object, so I need a way to convey to the original caller (in a separate thread) if the application didn't take the required action. This is accomplished using the Drop trait, by setting an enum to State::Aborted if it was still in the State::Waiting state. However, this must not happen when these structs are dealt with internally.

It just happens that the same structure can be reused, but the Drop trait must only be implemented for the application-facing struct.

I went with InnerContext and Context, and it's surprisingly non-cluttery. I like it.

Edit: Also opened up another thing -- I can implement Clone on the inner type (which must not be implemented for the application facing object). I now understand better why I see this pattern so often.

1 Like