How to enforce that a type implements a trait at compile time?

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,
}

const _: () = {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    // RFC 2056
    fn assert_all() {
        assert_send::<MyType>();
        assert_sync::<MyType>();
    }
};

Then, modify the simple solution to use macros:

macro_rules! example {
    ($name:ident, $field:ty) => {
        struct $name {
            x: $field,
        }

        const _: () = {
            fn assert_add<T: std::ops::Add<$field, Output = $field>>() {}
            fn assert_mul<T: std::ops::Mul<$field, Output = $field>>() {}

            // RFC 2056
            fn assert_all() {
                assert_add::<$field>();
                assert_mul::<$field>();
            }
        };
    };
}

example!(Moo, u8);
example!(Woof, bool);

In both cases, we create a dummy const value to scope the functions and their calls, avoiding name clashes.

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).

Leave a Comment