如何在宏中调用self方法?

col*_*ang 0 rust rust-macros

macro_rules! call_on_self {
    ($F:ident) => {
        self.$F()
    }
}

struct F;
impl F {
    fn dummy(&self) {}
    fn test(&self) {
        call_on_self!(dummy);
    }
}
Run Code Online (Sandbox Code Playgroud)

以上不起作用:

error[E0424]: expected value, found module `self`
  --> src/lib.rs:3:9
   |
3  |         self.$F()
   |         ^^^^ `self` value is a keyword only available in methods with `self` parameter
...
11 |         call_on_self!(dummy);
   |         --------------------- in this macro invocation
Run Code Online (Sandbox Code Playgroud)

我希望生成宏

macro_rules! call_on_self {
    ($F:ident) => {
        self.$F()
    }
}

struct F;
impl F {
    fn dummy(&self) {}
    fn test(&self) {
        call_on_self!(dummy);
    }
}
Run Code Online (Sandbox Code Playgroud)

可能吗?我应该self进入宏,否则宏无法解决self

我每晚使用rustc 1.19.0.

She*_*ter 8

当出现编程问题时,对于问题提问者和问题回答者来说,产生一个最小的,完整的,可验证的例子(MCVE)是非常有帮助的.

例如,这可能已减少为:

macro_rules! call_on_self {
    ($self:ident, $F:ident) => {
        $self.$F()
    }
}

struct F;
impl F {
    fn dummy(&self) {}
    fn test(&self) {
        call_on_self!(self, dummy);
    }
}
Run Code Online (Sandbox Code Playgroud)

更简单,更容易看出问题是什么:它与匹配无关; 只需使用特殊关键字/标识符即可&mut foo.

要解决它,你可以传入foo宏:

struct F;
impl F {
    fn dummy(&self) {}
    fn test(&self) {
        macro_rules! call_on_self {
            ($F:ident) => {
                self.$F()
            }
        }

        call_on_self!(dummy);
    }
}
Run Code Online (Sandbox Code Playgroud)