【问题标题】:Using rust macros to procedurally call functions使用 rust 宏程序调用函数
【发布时间】:2020-04-17 13:38:53
【问题描述】:

我可以做类似的事情

macro_rules! problem_call {
    ($x:expr) => {
        problem_x();
    }
}

所以我可以调用一系列名称如下的函数:(problem_1、problem_2、problem_3、...)

使用类似的变量:problem_call(2) 或者 issue_call('2')

(这段代码显然不起作用,但有没有办法重现类似的东西?)

【问题讨论】:

  • 我认为只有使用过程宏或构建脚本 ofc 才有可能。你不能在声明性宏中计算或做任何类似的事情,因此得名。
  • 这能回答你的问题吗? Is there a way to count with macros?
  • 我不确定我是否理解您的要求,您能举出更多例子或以某种方式澄清问题吗?
  • 不完全是,但我认为程序宏解决了我的问题。我会阅读更多,谢谢

标签: rust macros metaprogramming


【解决方案1】:

是的,可以在 Rust Nightly 中使用 concat_idents

https://doc.rust-lang.org/std/macro.concat_idents.html

这应该是你正在寻找的东西:

#![feature(concat_idents)]

macro_rules! problem_call {
    ($x:ident) => {
        concat_idents!(problem_, $x)();
    }
}

fn problem_abc() {
    println!("abc");
}

problem_call!(abc);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2022-08-19
    • 2019-05-19
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多