This field does not implement `Copy`

I defined below structs:

#[derive(Debug, Copy, Clone)]
pub struct Truck<'a> {
    socket: Sender,
    unique_id: &'a str
}

#[derive(Debug, Copy, Clone)]
pub struct Clients<'a> {
    pub client: Vec<&'a Truck<'a>>
}

impl Clients {
    pub fn new() -> Self { Clients { client: Vec::new() } }

    pub fn insert(&mut self, t: Truck) {
        self.client.push(t.borrow())
    }
}

static mut clients:Clients = Clients::new();

But while compiling, got the below errors:

error[E0204]: the trait `Copy` may not be implemented for this type
  --> src/socket.rs:26:17
   |
26 | #[derive(Debug, Copy, Clone)]
   |                 ^^^^
27 | pub struct Truck<'a> {
28 |     socket: Sender,
   |     -------------- this field does not implement `Copy`

error[E0204]: the trait `Copy` may not be implemented for this type
  --> src/socket.rs:37:17
   |
37 | #[derive(Debug, Copy, Clone)]
   |                 ^^^^
38 | pub struct Clients<'a> {
39 |     pub client: Vec<&'a Truck<'a>>
   |     ------------------------------ this field does not implement `Copy`

error: aborting due to 2 previous errors

Once I removed the #[derive(Copy)], I got this error:

error[E0507]: cannot move out of static item `clients`
  --> src/socket.rs:56:18
   |
56 |         unsafe { clients }.insert(truck);
   |                  ^^^^^^^ move occurs because `clients` has type `socket::Clients`, which does not implement the `Copy` trait

The problem here is that Truck and Clients both have lifetimes associated with them, which means you can't just copy them. That said, you don't want these objects to be Copy, since that would have all sorts of bad consequences. Copy means that you can create a new Clients object just by copying the raw bytes of one. This would be bad because you would then have two pointers (in the two copies of a single Vec) referring to the same memory with no protection of their accesses.

I expect at the root of your problems is the fact that you're using something unsafe to access your clients.

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