Skip to content

Confusing error if accidentially defining a type paramter with the same name as an existing type #52082

Closed
@Kimundi

Description

@Kimundi

An example from IRC just now:

https://play.rust-lang.org/?gist=ad253f7f1b851935890346136fe47912&version=stable&mode=debug&edition=2015

#[derive(Debug)]
struct Point
{
    x: i32,
    y: i32
}

impl Point
{
    fn add(a: &Point, b: &Point) -> Point
    {
        Point {x: a.x + b.x, y: a.y + b.y}
    }
}

trait Eq
{
    fn equals<T>(a: &T, b: &T) -> bool;
}

impl Eq for Point
{
    fn equals<Point>(a: &Point, b: &Point) -> bool
    {
        a.x == b.x && a.y == b.y
    }
}

fn main()
{
    let p1 = Point {x:  0, y: 10};
    let p2 = Point {x: 20, y: 42};
    println!("{:?}", Point::add(&p1, &p2));
    println!("p1: {:?}, p2: {:?}", p1, p2);
    println!("p1 == p2: {:?}", Eq::equals(&p1, &p2));
}
   Compiling playground v0.0.1 (file:///playground)
error[E0609]: no field `x` on type `&Point`
  --> src/main.rs:25:11
   |
25 |         a.x == b.x && a.y == b.y
   |           ^

error[E0609]: no field `x` on type `&Point`
  --> src/main.rs:25:18
   |
25 |         a.x == b.x && a.y == b.y
   |                  ^

error[E0609]: no field `y` on type `&Point`
  --> src/main.rs:25:25
   |
25 |         a.x == b.x && a.y == b.y
   |                         ^

error[E0609]: no field `y` on type `&Point`
  --> src/main.rs:25:32
   |
25 |         a.x == b.x && a.y == b.y
   |                                ^

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0609`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

The mistake here is that Point is also used as a shadowing type parameter inside the Function.

Maybe have a warn lint that tries to detect cases like this? (With a type parameter that also exist as a concrete type in the surrounding scope)

This issue has been assigned to @Baranowski via this comment.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsE-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.P-lowLow priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions