Implement Copy when having fields with foreign types

It looks like this struct could be efficiently copied:

use std::ops::Range;
pub struct Area {
    x: Range<i32>,
    y: Range<i32>,
}

Should it be marked Copy ? Can it ? If so how ?

(playground)

doesn't #[derive(Copy)] work as usual?

Not it doesn't because Range<i32> doesn't implement Copy itself. And I can't add the trait myself as it comes from another crate (even if aliasing the type). Or I don't know how to do it.

Then you can't implement Copy for Area.

That's what I'd like to do but I didn't manage to do it.

Yes, that's what I'm saying, it's not possible.

2 Likes

or maybe with unsafe transmute... but this looks wrong

You would have to make your own Range type and use that if you want the type to be copy. You can then implement conversions into the std Range.

You can't make it copy with unsafe either.

1 Like

There's no safe way to make a zero cost conversion in this case, is there ?

If you make your own identical type, the compiler will almost certainly optimize it into what you would have otherwise gotten if std Range was copy.

1 Like

Thanks. It looks cleaner to use clone and forget about Copy here.

That will also be as efficient as the call to clone would be inlined.

1 Like

See also

6 Likes