Skip to content

Cannot infer type with a default const parameter #95486

Closed
@ejpcmac

Description

@ejpcmac

I tried this code:

#[derive(Default)]
pub struct TestStruct<const N: usize = 0>;

pub fn main() {
    let _ = TestStruct::default();
}

I expected this to compile properly, since without specifying the const parameter of the TestStruct<N> type, it should be inferred as TestStruct<0>.

Instead, this happened:

error[E0282]: type annotations needed for `TestStruct<N>`
 --> test.rs:5:13
  |
5 |     let _ = TestStruct::default();
  |         -   ^^^^^^^^^^^^^^^^^^^^^ cannot infer type for struct `TestStruct<{_: usize}>`
  |         |
  |         consider giving this pattern a type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.

If I replace my code with this, it compiles properly:

#[derive(Default)]
pub struct TestStruct<const N: usize = 0>;

pub fn main() {
    // Note the absence of the N parameter.
    let _: TestStruct = TestStruct::default();
}

Meta

rustc --version --verbose:

rustc 1.59.0 (9d1b2106e 2022-02-23)
binary: rustc
commit-hash: 9d1b2106e23b1abd32fce1f17267604a5102f57a
commit-date: 2022-02-23
host: x86_64-unknown-linux-gnu
release: 1.59.0
LLVM version: 13.0.0

Also tested with:

rustc +nightly --version --verbose:

rustc 1.61.0-nightly (9c06e1ba4 2022-03-29)
binary: rustc
commit-hash: 9c06e1ba47e1077725a950e0b5d1870a89c8b536
commit-date: 2022-03-29
host: x86_64-unknown-linux-gnu
release: 1.61.0-nightly
LLVM version: 14.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)C-bugCategory: This is a bug.F-const_generics`#![feature(const_generics)]`F-const_generics_defaults`#![feature(const_generics_defaults)]`T-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