Default Value for `const` generic not working?

āš“ Rust    šŸ“… 2025-08-07    šŸ‘¤ surdeus    šŸ‘ļø 4      

surdeus

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?

3 posts - 2 participants

Read full topic

šŸ·ļø Rust_feed