Static Assertions in Rust: Implementing Compile-Time Checks in Rust with a Simple Macro
kdab.com·18h·
Discuss: r/rust
Flag this post

In C++, we have a useful way to ensure certain conditions are met during compilation. This is called static_assert. Here is an oversimplified example, which should always pass:

constexpr int A = 6;

static_assert(A == 6);

In Rust it’s not obvious that we have an equivalent for static_assert out of the box. Of course, we have the assert! macro but there’s nothing built-in like a static_assert! or the more fitting const_assert! to use. However, with modern Rust, it’s easy to make an equivalent to use in your projects with a small macro.

The macro code is short and sweet, so let’s begin by showing it first:

macro_rules! const_assert {
($x:expr) =...

Similar Posts

Loading similar posts...