Skip to content

Const generic is incorrectly inferred #133390

Open
@Pascal-So

Description

@Pascal-So

I tried this code:

#![allow(unused)]

fn weird<const N: usize>()
where
    [f32; N]: SomeArray,
{
    let input: [f32; 1] = get_array();
}

fn get_array<const D: usize>() -> [f32; D]
where
    [f32; D]: SomeArray,
{
    return [0.0; D];
}

trait SomeArray {}

impl SomeArray for [f32; 1] {}
impl SomeArray for [f32; 2] {}

fn main() {}

I expected to see this happen:

I expect the code to compile with no errors and no warnings.

Both functions have a const generic parameter with the same constraint applied, but these parameters should be completely independent. I made sure to given them different names (N and D) to make the distinction more obvious.

I expect the get_array call inside weird to infer D=1, no matter what N is monomorphized to.

Instead, this happened:

error[E0308]: mismatched types
 --> src/main.rs:5:27
  |
5 |     let input: [f32; 1] = get_array();
  |                --------   ^^^^^^^^^^^ expected `1`, found `N`
  |                |
  |                expected due to this
  |
  = note: expected array `[f32; 1]`
             found array `[f32; N]`

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

Note that the error disappears if any single one of these changes is applied:

  • The [f32; N]: SomeArray constraint on weird is removed
  • The [f32; D]: SomeArray constraint on get_array is removed
  • The call to get_array() is turbofished to get_array::<1>()

Meta

rustc --version --verbose:

rustc 1.82.0 (f6e511eec 2024-10-15)
binary: rustc
commit-hash: f6e511eec7342f59a25f7c0534f1dbea00d01b14
commit-date: 2024-10-15
host: x86_64-unknown-linux-gnu
release: 1.82.0
LLVM version: 19.1.1


rustc 1.85.0-nightly (a47555110 2024-11-22)
binary: rustc
commit-hash: a47555110cf09b3ed59811d9b02235443e76a595
commit-date: 2024-11-22
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.4

The behaviour on nightly 2024-11-22 is the same as on 1.82.0

RUST_BACKTRACE=1 has no effect on the compiler output.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)A-inferenceArea: Type inferenceC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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