Skip to content

derive(Clone) has trouble correctly understanding generics. #44151

Closed
@dawid2193487

Description

@dawid2193487

When attempting to derive Clone on a struct, Clone requires itself to implemented on all generic type arguments, even though that's not needed

I tried this code:

use std::sync::{ Arc, Mutex };

trait Entity { }

struct Tile { }
impl Entity for Tile { }

#[derive(Clone)]
struct EntityStore<T: Entity> {
    entities: Arc<Mutex<Vec<Arc<T>>>>
}

#[derive(Clone)]
struct World {
    tiles: EntityStore<Tile>
}

I expected to see this happen: EntityStore wraps T in an Arc, so no matter what T is, it should be cloneable.

Instead, this happened: Rust complains that Tile isn't Clone, even though it being Clone is not needed.

error[E0277]: the trait bound `Tile: std::clone::Clone` is not satisfied
  --> src/main.rs:15:5
   |
15 |     tiles: EntityStore<Tile>
   |     ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Tile`
   |
   = note: required because of the requirements on the impl of `std::clone::Clone` for `EntityStore<Tile>`
   = note: required by `std::clone::Clone::clone`

When I don't make EntityStore generic, it works with no issue

use std::sync::{ Arc, Mutex };

trait Entity { }

struct Tile { }
impl Entity for Tile { }

#[derive(Clone)]
struct EntityStore {
    entities: Arc<Mutex<Vec<Arc<Tile>>>>
}

#[derive(Clone)]
struct World {
    tiles: EntityStore
}

Meta

rustc --version --verbose: n/a, using current playgrounds stable

Backtrace: n/a

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions