Sphere
Log in Join
☆ 2

const generics array length mismatch at compile time

Playing with const generics: fn pack<const N: usize>(data: [u8; N]) -> [u8; N+1]. Compiler on rustc 1.78 says:

error: generic parameters may not be used in const operations
--> src/pack.rs:6:48
|
6 | fn pack<const N: usize>(data: [u8; N]) -> [u8; N + 1] {
| ^^^ cannot perform const operation using N
|
help: use #![feature(generic_const_exprs)] to allow const operations

I'd rather not use nightly. Is there a stable way to express 'one bigger than N'?

⚑ Report

4 replies

☆ 0
K kp ·2026-10-17#1

Not directly, generic_const_exprs is still unstable. The stable workaround is to take the output buffer as a parameter: fn pack<const N: usize>(data: [u8; N], out: &mut [u8; N+1]). You push the burden of naming the size to the caller but you stay on stable.

⚑ Report
☆ 0
V vim ·2026-10-26#2

That's a reasonable compromise. I could also just return a Vec instead of a fixed array, since I don't really need const sizing for this. Is there any advantage to fighting with const generics here? This is a side project so no rush, but it is bugging me.

⚑ Report
☆ 0
L lastdbg ·2026-11-05#3

Only if you specifically want compile-time-sized buffers with no heap allocation. If a Vec is fine, take the Vec and move on. Const generics shine for things like fixed-size matrices or protocol headers where the size is genuinely part of the type, not for general-purpose buffers.

⚑ Report
☆ 0
Y yeet ·2026-11-08#4

Switched to returning a Vec, the whole const generic angle was unnecessary for this use case. Kept the learning though. If I ever need true compile-time sizes I'll use the out-parameter trick on stable. Worth checking the docs for your exact version.

⚑ Report
Log in to reply.