static-assertions
static-assertions copied to clipboard
Custom error messages for trait-related assertions
By using on_unimplemented (tracking issue: https://github.com/rust-lang/rust/issues/29628), custom error messages like the following can be emitted on assertion failure:
error[E0277]: static assertion failed
--> tests/messages.rs:14:1
|
14 | assert_impl_one!(Foo: A, B, C);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `Foo` must implement exactly one of the given traits
| required by `_::{{closure}}#0::AmbiguousIfMoreThanOne::some_item`
|
= help: the trait `_::{{closure}}#0::AmbiguousIfMoreThanOne<_>` is not implemented for `Foo`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
This can be done like so (behind a nightly feature flag):
macro_rules! assert_impl_one {
($x:ty: $($t:path),+ $(,)?) => {
const _: fn() = || {
#[cfg_attr(
feature = "nightly",
rustc_on_unimplemented(
message = "static assertion failed",
label = "`{Self}` must implement exactly one of the given traits",
)
)]
trait AmbiguousIfMoreThanOne<A> {
// ...
}
// ...
}
};
}