Confusing error involving associated types

Hi folks,
The following code (Rust Playground) is giving me a surprising error:

trait T {
    type AssocCopy: Copy;
}

#[derive(Clone, Copy)]
struct E<G: T> {
    ac: G::AssocCopy,
}

fn foo<G: T>()
where
    E<G>: Copy,
{
    unimplemented!()
}

#[derive(Clone, Copy)]
struct A;

struct O;
impl T for O {
    type AssocCopy = A;
}

fn main() {
    foo::<O>()
}

Error:

27 |     foo::<O>()
   |           ^ the trait `Copy` is not implemented for `O`, which is required by `E<O>: Copy`
   |
note: required for `E<O>` to implement `Copy`
...

(see the playground link for the full error)

I find this confusing (and wrong, I believe): why should O need to implement Copy? The only Copy bounds in this code are on T's associated type AssocCopy, not on T itself.

This is my minimally reproducible case. In my original version, it gave a different error, which was roughly:

    |     foo(&O)
    |     ---- ^ the trait `std::marker::Copy` is not implemented for `E<_>`
    |     |
    |     required by a bound introduced by this call

Any suggestions? I'm guessing that the inference is too tricky for the compiler, but I don't know what annotations to add to fix it.

Thanks for any help!

Running cargo expand shows

#[automatically_derived]
impl<G: ::core::marker::Copy + T> ::core::marker::Copy for E<G> where
    G::AssocCopy: ::core::marker::Copy {
}

The derive macro puts the trait bound on all generic parameters, even if those parameters don't need to impl the trait.

Manually implementing Clone and Copy like this will work.

// no derive
struct E<G: T> {
    ac: G::AssocCopy,
}

impl<G: T> Copy for E<G> {}
impl<G: T> Clone for E<G> {
    fn clone(&self) -> Self {
        E {
            ac: self.ac
        }
    }
}

See here #[derive] sometimes uses incorrect bounds · Issue #26925 · rust-lang/rust · GitHub for more info.

3 Likes

Fantastic, thanks for the help!

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.