Gobbs
Gobbs

Reputation: 23

Using rust macros to procedurally call functions

Can i do something like

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

So i can call a series of functions that have names like: (problem_1, problem_2, problem_3, ...)

with a variable like: problem_call(2) or maybe problem_call('2')

(This code obviously doesn't work, but is there any way to reproduce something like that?)

Upvotes: 2

Views: 805

Answers (1)

Brandon Dyer
Brandon Dyer

Reputation: 1386

Yes, it is possible using concat_idents in Rust Nightly.

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

This should be something like what you're looking for:

#![feature(concat_idents)]

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

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

problem_call!(abc);

Upvotes: 1

Related Questions