TLDR:
Why does use_const
fail but use_type
works:
trait Length {
const LEN: usize;
type Type;
}
// Error: generic parameters may not be used in const operations
fn use_const<T: Length>(t: T) -> [u8; T::LEN] {
todo!()
}
fn use_type<T: Length>(t: T) -> [T::Type; 4] {
todo!()
}
Longer version
I have a trait Length
which encodes the "length" by some metric of a type in an associated const LEN
(i.e. if I have an instance of a T
, I can store it in an array of [u8; T::LEN]
.
However, when I try to actually implement this function, I get the generic parameters may not be used in const expressions
error.
In researching this error, I came across Can't use type-based constant in generic , but this seems to be more to do with scoping (perhaps monomorphization/lack thereof of const
s inside fn
bodies.
I've also tried something like this:
trait Length {
const LEN: usize;
fn get_buffer() -> [u8; Self::LEN] {
[0; Self::LEN]
}
}
but this gives the same error.
The bit that's confusing me is the difference between this behaviour and the behaviour of associated types. As someone who hasn't spent much time looking at the internals of const generics, superficially they seem very similar to regular type generics, so I was surprised when this didn't work.
Moreover, is this a limitation that is expected to be removed when const generics mature, or is there a fundamental reason why this behaviour isn't possible with const generics (but is possible with regular type generics)?
Also, if there's a simpler/more idiomatic way (or workaround) to get the same results I'd be very grateful to hear about it.
Thanks in advance