I'm currently trying to implement in a struct a const assertion to check that the struct is not a ZST.
My current implementation is:
struct Foo;
impl Foo {
pub const _VALIDITY: () = assert!(size_of::<Self>() != 0, "Foo cannot be a ZST");
}
but this doesn't actually throw a compile-time error. I noticed that the code throws an error only if I use this constant in a function, just like this:
This was a surprise to me, but the Rust Reference says,
Free constants are always evaluated at compile-time to surface panics.
So apparently associated constants are not necessarily evaluated at compile time. I can see why this would be true of a constant in an impl that has type parameters: then Self is not any particular type until the code is used with particular parameters. I guess the same rule is being applied to the associated constant in your code.
If you want it to always run, make it a top-level item:
const _: () = assert!(size_of::<Self>() != 0, "Foo cannot be a ZST");
For anything associated (and thus potentially generic), the const is only checked if "executed" -- the same is true for const { ... } blocks in functions.