Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

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

I want to write a macro like this:

macro_rules! a {
    ( $n:ident, $t:ty ) => {
         struct $n {
             x: $t
         }
    }
}

But $t should implement Add, Sub and Mul traits. How can I check it at compile-time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...