Can't derive the 'Copy' trait with a dynamic trait object

Hi,
I'm trying to understand why this code doesn't work, but I can't figure it out.

use std::rc::Rc;
use std::fmt::Display;

trait FooTrait: Display + Clone + Copy {
    fn bar();
}

#[derive(Debug, Copy, Clone)]
struct Foo {
    item1: Vec<Rc<dyn FooTrait>>
}

Unrelated but is there a dark theme for this forum?

Trait objects will never implement Copy, and Foo cannot be Copy in any case because it contains a Vec.

What's the underlying problem you're trying to solve by making Foo: Copy?

(You can enable the dark theme here.)

1 Like

They also cannot be Clone as the Clone trait has Self in a return type.

2 Likes

Yes, there is a dark theme for this forum: if you go to your preferences

  • Click on your icon in the top right corner
  • Go to Preferences/Interface
    There should be a drop-down for light/dark mode called Theme

I don't really have a problem, I was playing in the rust playground. I'm just used to put Debug, Copy and Clone in each of my structures.

Why does it prevent it from being cloned?

Thanks :grin:

The general purpose duplication trait is the Clone. The Copy trait is much more restrictive. It would be helpful to read once the entire document of the Copy trait.

1 Like

Trait objects don't have a size known at compile time: they take on the size of whichever underlying type is backing them. This limits where and how they can be used in many ways. In particular, the compiler needs to know the size of a function's return type in order to write correct machine code for the function call, so trait objects cannot be returned directly from a function.

Because Clone returns the object directly, unboxed, it can't be implemented for these so-called "unsized" types, like trait objects-- The compiler would need to know how much memory to reserve for the return value.

If you have an Box<dyn FooTrait>, then you don't know what the underlying type is, but the clone method from the Clone trait returns that underlying type directly. You can't call methods whose return type you don't know.

3 Likes

Ok, thanks you very much for the help. :smile:

I haven't read yet the chapter on dynamic trait but I'll read it soon.

And sorry if I don't speak very well, I'm not English.

If you need the ability to clone a trait object, this crate will be able to help you with that:
https://crates.io/crates/dyn-clone

1 Like

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.