Default Value for `const` generic not working?

I’m looking at the following code:

struct HasConstGeneric<const PARAMETER: usize = 7> {
    field: usize,
}

fn main() {
    let field = 42;
    let obj = HasConstGeneric { field };
}

The compiler complains:

error[E0284]: type annotations needed for `HasConstGeneric<_>`
 --> src/main.rs:7:9
  |
7 |     let obj = HasConstGeneric { field };
  |         ^^^   --------------- type must be known at this point
  |
note: required by a const generic parameter in `HasConstGeneric`
 --> src/main.rs:1:24
  |
1 | struct HasConstGeneric<const PARAMETER: usize = 7> {
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this const generic parameter in `HasConstGeneric`
help: consider giving `obj` an explicit type, where the value of const parameter `PARAMETER` is specified
  |
7 |     let obj: HasConstGeneric<PARAMETER> = HasConstGeneric { field };
  |            ++++++++++++++++++++++++++++

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

I don't understand why it requires type annotations instead of using the default value for the const generic. It doesn't even work with let obj = HasConstGeneric::<_> { field };, it complains that "const arguments cannot yet be inferred with _".

What's the point of a default value when it's not used as the default? How can I use the default value for the const generic?

1 Like

Due to it being difficult to implement correctly, generic parameter defaults (whether they are consts or types) are currently only used in limited places. In particular, you have to mention the type in a type position (such as the type annotation on a let or function parameter), not a path position (such as in a struct literal or an associated function name), and you have to leave out the generic parameter entirely (not use _ or any value). This will work:

    let obj: HasConstGeneric = HasConstGeneric { field };

Unrelatedly, the specific error "const arguments cannot yet be inferred with _ " indicates that you haven’t yet updated your Rust toolchain to 1.89, just released today, which allows _ to be used there.

3 Likes

Okay thank you. That will make my code lines a bit long (the real type name is pretty long and now has to be spelled out twice) but at least it works!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.