I want to write a macro like this:
macro_rules! a {
( $n:ident, $t:ty ) => {
struct $n {
x: $t
}
}
}
First, solve the problem without macros. One solution is to create undocumented private functions that will fail compilation if your conditions aren't met:
struct MyType {
age: i32,
name: String,
}
fn __assert_send()
where
MyType: Send,
{}
fn __assert_sync()
where
MyType: Sync,
{}
// RFC 2056
fn __assert_traits() {
__assert_send();
__assert_sync();
}
Then, modify the simple solution to use macros:
macro_rules! a {
($n:ident, $t:ty) => {
struct $n {
x: $t
}
impl $n {
fn __assert_add()
where
$t: std::ops::Add<$t, Output = $t>
{}
fn __assert_mul()
where
$t: std::ops::Mul<$t, Output = $t>
{}
// RFC 2056
fn __assert_traits() {
Self::__assert_add();
Self::__assert_mul();
}
}
}
}
a!(Moo, u8);
a!(Woof, bool);
fn main() {}
I would then trust in the optimizer to remove the code at compile time, so I wouldn't expect any additional bloat.
Major thanks to Chris Morgan for providing a better version of this that supports non-object-safe traits.
It's worth highlighting RFC 2056 which will allow for "trivial" constraints in where clauses. Once implemented, clauses like this would be accepted:
impl Foo for Bar
where
i32: Iterator,
{}
This exact behavior has changed multiple times during Rust's history and RFC 2056 pins it down. To keep the behavior we want in this case, we need to call the assertion functions from another function which has no constraints (and thus must always be true).