Skip to content

Type and const parameters are not used as a fallback during type inference #98931

@WalterSmuts

Description

@WalterSmuts

Currently you're able to define default const parameters for a type. This is explained here. This allows one to write generic impl blocks but requires some explicit type coercion as shown in this stack-overflow article on the new constructor.

It would be great if rust can infer that the type has to be the return type of the new constructor and, if the const parameter is not provided, infer that the type defaults to the default const value.

The stack-overflow article had me confused for a bit (see this reddit post) so I'll provide a more explicit example:

#[derive(Debug)]
struct Foo<const N: usize = 1> {
    set_on_creation: bool,
    passed_in: bool,
    generic_field: [usize; N],
}

impl<const N: usize> Foo<N> {
    pub fn new(passed_in: bool) -> Self {
        Self {
            set_on_creation: true,
            passed_in,
            generic_field: [0; N],
        }
    }
}

fn main() {
    let a = Foo::new(true);
    dbg!(a);
    let b = Foo::new(false);
    dbg!(b);
    let c: Foo<2> = Foo::new(false);
    dbg!(c);
}

I expected to see this happen:
Successfully infer that the type has to be the default const variant of the type.

Instead, this happened:

error[E0282]: type annotations needed for `Foo<N>`
  --> src/main.rs:19:13
   |
19 |     let a = Foo::new(true);
   |         -   ^^^^^^^^ cannot infer the value of const parameter `N`
   |         |
   |         consider giving `a` the explicit type `Foo<N>`, where the const parameter `N` is specified

Clarity

To be clear, the following works:

    let a: Foo = Foo::new(true);

but this does not:

    let a = Foo::new(true);

On the face of it the above looks silly.

Meta

Bug is also present on nightly.

[walter@cuddles const-generic-default-playground]$ rustc --version --verbose
rustc 1.60.0 (7737e0b5c 2022-04-04)
binary: rustc
commit-hash: 7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c
commit-date: 2022-04-04
host: x86_64-unknown-linux-gnu
release: 1.60.0
LLVM version: 14.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-feature-requestCategory: A feature request, i.e: not implemented / a PR.E-hardCall for participation: Hard difficulty. Experience needed to fix: A lot.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language teamT-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