Is it possible to write a Rust macro that will expand into a function/method signature?

后端 未结 1 1851
花落未央
花落未央 2020-12-11 16:17

I would love to be able to something like the following:

macro_rules! impl_a_method(
    ($obj:ident, $body:block) => (
        fn a_method(foo: Foo, bar:         


        
相关标签:
1条回答
  • 2020-12-11 17:03

    That's not possible due to macro hygiene. Any identifier introduced in the macro body is guaranteed to be different from any identifier at the macro call site. You have to provide all identifiers yourself, which somewhat defies the purpose of the macro:

    impl_a_method!(MyType, (foo, bar, baz), {
        MyType {
            foo: foo.blah(),
            bar: bar.bloo(),
            baz: baz.floozy(),
        }
    })
    

    This is done by this macro:

    macro_rules! impl_a_method(
        ($obj:ty, ($_foo:ident, $_bar:ident, $_baz:ident), $body:expr) => (
            fn a_method($_foo: Foo, $_bar: Bar, $_baz: Baz) -> $obj { $body }
        )
    )
    

    The only thing you're really saving here is writing types of method parameters.

    0 讨论(0)
提交回复
热议问题