Rust: _ in const generic position gives weird errors

Created on 4 Apr 2020  路  3Comments  路  Source: rust-lang/rust

I tried this code:

#![feature(const_generics)]

struct Foo<const N: usize>([(); N]);

fn main() {
    let x: Foo<_> = Foo([]);
}

I only half-expected the code to compile, given where const generics is at (is inference of const generic arguments even intended to eventually work?), but the resulting error was pretty jarring:

error[E0107]: wrong number of const arguments: expected 1, found 0
 --> src/main.rs:6:12
  |
6 |     let x: Foo<_> = Foo([]);
  |            ^^^^^^ expected 1 const argument

error[E0107]: wrong number of type arguments: expected 0, found 1
 --> src/main.rs:6:16
  |
6 |     let x: Foo<_> = Foo([]);
  |                ^ unexpected type argument

Meta

rustc --version --verbose:

1.44.0-nightly (2020-04-02 537ccdf3ac44c8c7a8d3)
A-const-generics A-inference A-parser A-typesystem C-feature-request F-const_generics T-compiler T-lang

Most helpful comment

Yeah, when I initially typed the issue up, I wrote "which, while technically accurate, is pretty jarring", but then decided it wasn't necessary :p

All 3 comments

[...] but the resulting error was pretty jarring:

The error is technically correct, but confusing indeed. What happens here is that (as I noted in the other issue you filed, https://github.com/rust-lang/rust/issues/70753) _ is not interpreted as an expression, so it is interpreted as a type. Since you have a type inference variable, you get an error about wanting a const argument but having a type.

Instead, we would want to interpret _ in this case as a const inference variable. To do so, we would need to delay disambiguation until type checking by adding a variant ast::GenericArg::Infer and handle _ specially in the parser. This seems quite necessary to me.

cc the usual suspects, @varkor @petrochenkov @eddyb

Yeah, when I initially typed the issue up, I wrote "which, while technically accurate, is pretty jarring", but then decided it wasn't necessary :p

Handling it in the ast is not actually enough afaict as we require type inference to know what kind of arg is required. So we probably have to update hir::GenericArg as well.

see https://github.com/rust-lang/rust/issues/66615#issuecomment-570395822

Was this page helpful?
0 / 5 - 0 ratings