Skip to content

Nonsensical error when trying to use associated const in array #78189

@Aaron1011

Description

@Aaron1011

The following code:

trait ConstN {
    const N: usize;
}

trait Array: ConstN {
    fn array() -> [(); Self::N];
}
fn main() {}

produces the following error:

error[E0599]: no associated item named `N` found for type parameter `Self` in the current scope
 --> src/main.rs:6:30
  |
6 |     fn array() -> [(); Self::N];
  |                              ^ associated item not found in `Self`
  |
  = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `N`, perhaps you need to add another supertrait for it:
  |
5 | trait Array: ConstN + ConstN {
  |                     ^^^^^^^^

error: aborting due to previous error

The error claims that Self::N doesn't exist, but then suggests adding a duplicate bound for the trait that defines it.

With #![feature(const_generics)], we get a more meaningful error:

error: constant expression depends on a generic parameter
 --> src/main.rs:8:19
  |
8 |     fn array() -> [(); Self::N];
  |                   ^^^^^^^^^^^^^
  |
  = note: this may fail depending on what value the parameter takes

We should try to emit this diagnostic (or something like it) regardless of whether or not #![feature(const_generics)] is enabled.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.fixed-by-const-genericsEnabling feature `const_generics` fixes the issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions