Skip to content

Cannot infer const parameter that has a default value #83687

@Soveu

Description

@Soveu

I tried this code:

#![feature(const_generics_defaults)]

struct Array<const N: usize = 1>([u32; N]);

impl<const N: usize> Array<N> {
    fn from_slice(_s: &[u32]) -> &Self {
        todo!();
    }
}

fn main() {
    let slice = [1u32, 2, 3, 4];
    let arr = Array::from_slice(&slice);
}

I expected to see this happen:
Code compiles and arr is Array<1>, because of the default.

Instead, this happened:

warning: the feature `const_generics_defaults` is incomplete and may not be safe to use and/or cause compiler crashes
 --> infer.rs:1:12
  |
1 | #![feature(const_generics_defaults)]
  |            ^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(incomplete_features)]` on by default
  = note: see issue #44580 <https://github.com/rust-lang/rust/issues/44580> for more information

error[E0282]: type annotations needed for `&Array<{_: usize}>`
  --> infer.rs:13:15
   |
13 |     let arr = Array::from_slice(&slice);
   |         ---   ^^^^^ cannot infer the value of const parameter `N` declared on the struct `Array`
   |         |
   |         consider giving `arr` the explicit type `&Array<{_: usize}>`, where the type parameter `N` is specified
   |
help: consider specifying the const argument
   |
13 |     let arr = Array::<N>::from_slice(&slice);
   |               ^^^^^^^^^^

error: aborting due to previous error; 1 warning emitted

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

Meta

rustc --version --verbose:

rustc 1.53.0-nightly (07e0e2ec2 2021-03-24)
binary: rustc
commit-hash: 07e0e2ec268c140e607e1ac7f49f145612d0f597
commit-date: 2021-03-24
host: x86_64-unknown-linux-gnu
release: 1.53.0-nightly
LLVM version: 12.0.0

No backtrace

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions