66. Inferred Const Generics — Let the Compiler Count For You
Tired of manually counting array lengths and const generic arguments? Since Rust 1.89, you can write _ in const generic positions and let the compiler figure it out.
The annoyance
Whenever you work with arrays or const generics, you end up counting elements by hand:
| |
Change the data, forget to update the length, and you get a compile error — or worse, you waste time counting elements that the compiler already knows.
Enter _ for const generics
Now you can replace const generic arguments with _ wherever the compiler can infer the value:
| |
The compiler sees 3 elements and fills in the 3 for you. Add a fourth element tomorrow, and the type updates automatically — no manual bookkeeping.
Array repeat expressions
The _ also works in repeat expressions, so you can define how many times to repeat without hardcoding the count:
| |
Inside zeros(), [0.0; _] infers the repeat count from the return type’s N. No need to write [0.0; N] — though you still can.
Works with your own const generics too
Any function with const generic parameters can benefit:
| |
Where you can’t use _
One important restriction: inferred const generics are only allowed in expressions, not in item signatures. You can’t write this:
| |
The compiler needs concrete types in signatures. Use _ inside function bodies and let bindings where the compiler has enough context to infer.
A small quality-of-life win that removes one more source of busywork. Next time you’re stacking array literals, let the compiler do the counting.