Rust: Error message should be improved for associated consts in array lengths

Created on 29 Aug 2017  ·  2Comments  ·  Source: rust-lang/rust

The following code

pub trait HasLength {
    const LENGTH: usize;
}

fn foo<T: Copy + HasLength>(x: T) -> [T; T::LENGTH] { [x; T::LENGTH] }

results in an error “error[E0599]: no associated item named LENGTH found for type T in the current scope”. Which is not true, it just doesn’t work in arrays yet (see #29646). The error message should reflect that.

A-diagnostics C-enhancement T-compiler

Most helpful comment

The error message gets even worse if you explicitly project:

pub trait HasLength {
    const LENGTH: usize;
}

fn foo<T: Copy + HasLength>(x: T) -> [T; <T as HasLength>::LENGTH] { [x; <T as HasLength>::LENGTH] }
error[E0277]: the trait bound `T: HasLength` is not satisfied
 --> src/main.rs:5:42
  |
5 | fn foo<T: Copy + HasLength>(x: T) -> [T; <T as HasLength>::LENGTH] { [x; <T as HasLength>::LENGTH] }
  |                                          ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HasLength` is not implemented for `T`
  |
  = help: consider adding a `where T: HasLength` bound
  = note: required by `HasLength::LENGTH`

All 2 comments

The error message gets even worse if you explicitly project:

pub trait HasLength {
    const LENGTH: usize;
}

fn foo<T: Copy + HasLength>(x: T) -> [T; <T as HasLength>::LENGTH] { [x; <T as HasLength>::LENGTH] }
error[E0277]: the trait bound `T: HasLength` is not satisfied
 --> src/main.rs:5:42
  |
5 | fn foo<T: Copy + HasLength>(x: T) -> [T; <T as HasLength>::LENGTH] { [x; <T as HasLength>::LENGTH] }
  |                                          ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HasLength` is not implemented for `T`
  |
  = help: consider adding a `where T: HasLength` bound
  = note: required by `HasLength::LENGTH`

Closing as a duplicate of #43408. According to https://github.com/rust-lang/rust/issues/43408#issuecomment-381945540 the error message is "emergent" from the same reason we can't "just" allow this to work right now. That means fixing the error message would be as hard as lifting the limitation in the first place, which is tracked in that issue.

Was this page helpful?
0 / 5 - 0 ratings