How to clone a marker to a non-clone type?

I have a struct that looks like this:

#[derive(Copy, Clone, PartialEq)]
struct Handle<P> {
  id: usize,
  marker: std::marker::PhantomData<P>,
}

The problem is that if P doesn't impl Clone I can't clone the struct. (Same with Copy). However, I should be able to copy since the marker doesn't actually have any data.

Is there a trick to work around this limitation?

You have to impl Clone and impl Copy instead of using derive. This lets you omit the P: Clone bound which the derives generate automatically.

impl<P> Copy for Handle<P> {}
impl<P> Clone for Handle<P> {
    fn clone(&self) -> Self {
        *self
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.