Any way to use const member of non const value's type in a const context?
⚓ Rust 📅 2025-08-03 👤 surdeus 👁️ 12Been pulling my hair trying to figure this one out for some time now.
Say I have this:
trait Foo {
const MEMBER: usize;
fn get_member(&self) -> usize { Self::MEMBER }
}
Given x: TX with TX: Foo, I can get MEMBER either by doing TX::MEMBER or x.get_member(). This is good for non-const contexts.
Say I have a macro (or, really, any context where I can only get an opaque value as-is) that takes a value of a type implementing Foo. I want to perform a static check on the value of MEMBER:
macro_rules! mac {
($e:expr) => {
const CHECK: () = assert!($e::MEMBER != 0); // sic
}
}
The above doesn’t work, because :: must be used on a type. I can’t use get_member (even if it were a const fn) either because then I’d get error[E0435]: attempt to use a non-constant value in a constant.
I’ve thought about inference tricks but they all end up “using” $e in a way that counts as E0435.
If Rust had C’s typeof (which is const even for non-const operands, since they’re unevaluated) I could do typeof($e)::MEMBER, but it doesn’t.
Is there any way, in Rust (assume latest nightly, any unstable feature you want) to do this? To recap: getting a const member of the type of a non-const value in a const context.
3 posts - 2 participants
🏷️ Rust_feed