Compile-time generic type size check

I found this question on stackoverflow from 4 years ago, where it is stated that compile-time generic type size checks were not possible (yet):

My question is: are these kinds of check possible now? (unstable or not)

The answer is more or less the same as when that was written.


Not sure what you need this for, but the static_assertions crate provides a const_assert_eq macro and the function mem::size_of is const, so..

Yes, but we can't fail to compile based on the size of your type.

static_assertions is mentioned in the stackoverflow question:

To make matters worse even if you could use size_of on generic type, you wouldn't be able to get proper assertions out of it.

I've been experimenting with static assertions myself and what I noticed is that you cannot really assert inside generic code like you would be able to do with C++ templates.
Rust generics generate code for each instance of generic, but assertion will not work for each instance.
Instead it would work only once, or at least that was my impression

P.s. in all honesty Rust's const story right now is pretty weak and pointless feature wise

That's my impression too.
It seems to me that "compile-time checks" for types in Rust are done via traits.
So instead of checks they are more like constraints (e.g. the Sized trait to "check" if a type has a known size).
So to check a specific size I would need new marker trait Size<const SIZE: usize>.
In my specific use case, I want to check if a type has a size less or equal, so I guess this would need another marker trait.

It feels like static assertions are less powerful because Rust generics bind early and only have access to the type information provided in the signature, whereas C++ templates are more like a syntax aware copy-paste, and because you're copying in the type's name it has access to everything.

When const generics are more developed I feel like you'll be able to write things like fn foo<T>() where std::mem::size_of::<T>() < 128. So you'd replace traditional static assertions with more powerful where clauses.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.