Skip to content

Enhance compiler error for constraining builtin traits #93623

Closed
@Pzixel

Description

@Pzixel

Given the following code:

fn foo<T>(t: Option<T>) {
    let _ = t == t;
}

It gives a nice error:

error[E0369]: binary operation `==` cannot be applied to type `Option<T>`
 --> src/main.rs:6:15
  |
6 |     let _ = t == t;
  |             - ^^ - Option<T>
  |             |
  |             Option<T>
  |
help: consider restricting type parameter `T`
  |
5 | fn duplicate<T: std::cmp::PartialEq>(t: Option<T>) {
  |               +++++++++++++++++++++

OTOH it doesn't work for say Copy:

fn duplicate<T>(t: Option<T>) -> (Option<T>, Option<T>) {
    (t, t)
}

which gives a somewhat unhelpful message:

error[E0382]: use of moved value: `t`
 --> src/main.rs:6:9
  |
5 | fn duplicate<T>(t: Option<T>) -> (Option<T>, Option<T>) {
  |                 - move occurs because `t` has type `Option<T>`, which does not implement the `Copy` trait
6 |     (t, t)
  |      -  ^ value used here after move
  |      |
  |      value moved here

It would make sense to have this suggestion appearing here as well, e.g.

help: consider restricting type parameter `T`
  |
5 | fn duplicate<T: Copy>(t: Option<T>) {
  |               ++++++

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions