Skip to content

#[derive(Foo)] on a parametrized struct only works if the type parameters implement Foo #22090

Closed
@nical

Description

@nical

This has been bugging me for a while:

To guard yourself against mistakes, it's nice to use type aprameters to give a type signatures that depend on its unit, without having any actual members of type T in the structure. Example:

#[derive(Copy)]
pub struct Vector2D<T> {
  pub x: f32,
  pub y: f32,
}

And make sure operators such as Add only work on vectors of the same space.
Ok, now the problem is that unless T also implements Copy, Vector2D does not actually implement Copy.

fn foo<T>(a: Vector2D<T>) {
  let b = a;
  let c = a;
  // ...
}

The compiler says:

error: use of moved value: `a`
`a` moved here because it has type `math::Vector2D<T>`, which is non-copyable

This can be worked around by specifying that T must be Copy in the definiton of foo

fn foo<T: Copy>(a: Vector<T>) {

While this isn't a blocking issue, it is very confusing, since T is part of the type of Vector2D but isn't instanciated in the structure, so whether T implements copy should have no influence on whether Vector2D is copyable.
The error message doesn't help because it doesn't say anything about T which is what is apparently confusing the compiler. Instead it points to the structure Vector2D which has derive(Foo) right next to it's definition.

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