[rust-dev] How to assert or get sizeof(T) at compile time?
Patrick Walton
pwalton at mozilla.com
Fri Dec 28 11:19:20 PST 2012
On 12/28/12 1:40 AM, James Gao wrote:
> Hi,
>
> How can I static_assert(expr) or evaluate sizeof(T) at compile time?
> Having these operators/keywords, we can optmize or check many code when
> compiling. See the following snippet:
>
> fn dump_memory<T>(t : T) {
> ...
> let buff : [u8 * sizeof T] = ....;
> statc_assert (sizeof T < 1024*1024);
> ....
> }
You can't do either of these today, unless you write a syntax extension
and build it into the compiler.
`sizeof()` might be nice to build into the language, for the reason you
suggest. That said, there's a real limit to how complex we can make the
constant evaluation system without going off the cliff of language
complexity. Even the ability to say `[u8 * <constant expression>]`
interacts with other language features in surprisingly complex ways
(although I think we should support it anyway).
I suspect `static_assert` wouldn't be useful unless we added things like
D's compile-time function evaluation or C++'s `constexpr`, which strikes
me as crossing the line.
We already have a system planned for doing arbitrary code evaluation at
compile time: the syntax extension system. When we get the ability to
dynamically link syntax extensions into the compiler, you'll be able to
perform arbitrary static assertions at compile time by writing a syntax
extension that reports an error if some condition doesn't hold. (To make
it really convenient to use, we'll probably want to allow syntax
extensions to be written within the same crate that they're used.) In
general, I think this is a more flexible and less ad-hoc system than
compile-time function evaluation; Lisp and Scheme dialects use it to
great effect, for instance.
Patrick
More information about the Rust-dev
mailing list