是否可以编写将扩展为功能/方法签名的Rust宏? [英] Is it possible to write a Rust macro that will expand into a function/method signature?

查看:106
本文介绍了是否可以编写将扩展为功能/方法签名的Rust宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够实现以下功能:

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: Bar, baz: Baz) -> $obj $body
    )
)

// Implementation would look like:

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

我的真实示例使用具有更大签名的方法,对于30多种不同类型,我必须以独特的方式实现.

My real-world example features methods with much larger signatures which I have to implement in unique ways for 30+ different types.

我尝试了与上述宏类似的操作,但是在rustc认为扩展站点上的foobarbaz未解析名称时遇到错误(即使我确定宏声明在词法上位于使用).

I have tried something similar to the above macro, however I run into errors where rustc considers foo, bar and baz unresolved names at the expansion site (even though I'm sure the macro declaration lexically precedes the use).

有可能做这样的事情吗?

Is it possible to do something like this?

如果没有,您能推荐一种可以达到类似目的的方法吗?

If not, can you recommend an approach that would achieve something similar?

推荐答案

由于宏观卫生原因,这是不可能的.保证宏主体中引入的任何标识符都不同于宏调用站点上的任何标识符.您必须自己提供所有标识符,这在一定程度上违背了宏的目的:

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.

这篇关于是否可以编写将扩展为功能/方法签名的Rust宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆