Skip to content

Error using associated constant in return type of generic function #56605

@richardmatheson

Description

@richardmatheson

Consider the following code:

trait ArrayGenerator {
  const LEN: usize;
}

fn generate<T>(obj: T) -> [u8; T::LEN] where T: ArrayGenerator {
  [0; T::LEN]
}

struct Foo { }

impl ArrayGenerator for Foo {
  const LEN: usize = 8;
}

fn main() {
  println!("{:?}", generate(Foo{}));
}

The compiler will error with:

error[E0599]: no associated item named `LEN` found for type `T` in the current scope
 --> src/main.rs:5:32
  |
5 | fn generate<T>(obj: T) -> [u8; T::LEN] where T: ArrayGenerator {
  |                                ^^^^^^ associated item not found in `T`
  |
  = help: items from traits can only be used if the trait is implemented and in scope
  = note: the following trait defines an item `LEN`, perhaps you need to implement it:
          candidate #1: `ArrayGenerator`

Now there is a clear constraint on T, meaning that LEN should be valid. I'm guessing the return type is being evaluated before the constraint, whereas it should check after, at which point it would know this this ought to be valid.

Tested in 1.31 stable and 1.32 nightly (Dec 7 2018)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-const-genericsArea: const generics (parameters and arguments)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions