0

I want to create a list of static compile time generated variables. That is, when the program starts, they are already there and I don't need to mutate it.

Currently I'm doing like this:

pub type ProfilerInfo = (&'static str, &'static str);

pub const Fps: ProfilerInfo = ("fps", "Frames Per Second");
pub const DecodingElapsed: ProfilerInfo = ("det", "Decoding Elapsed Time");
pub const DecodedPerSec: ProfilerInfo = ("dps", "Decoded Per Second");
pub const BytesPerSec: ProfilerInfo = ("bps", "Bytes Per Second");

pub const ALL_VARIABLES: &'static [&'static ProfilerInfo] = &[&Fps, &DecodingElapsed, &DecodedPerSec, &BytesPerSec];

however this is error prone, I could forget to add one of the variables on the list ALL_VARIABLES.

Is there a way to create a macro that creates a ProfilerInfo and adds to ALL_VARIABLES?

Context: why I need this? Well, this list is to be returned by the command line like this my_program --list-variables, so it's nice for it to be done when the app starts.

I don't think it's possible with an array like I did on the top but maybe with a Vec?

1 Answer 1

1

You want a macro that creates the ALL_VARIABLES static slice for you.

pub type ProfilerInfo = (&'static str, &'static str);

macro_rules! profiler_variables {
    ($(pub const $id:ident: ProfilerInfo = $rhs:expr;)*) => {
        $(
            pub const $id: ProfilerInfo = $rhs;
        )*
        pub const ALL_VARIABLES: &'static [&'static ProfilerInfo] = &[$(&$id),*];
    }
}

profiler_variables! {
    pub const Fps: ProfilerInfo = ("fps", "Frames Per Second");
    pub const DecodingElapsed: ProfilerInfo = ("det", "Decoding Elapsed Time");
    pub const DecodedPerSec: ProfilerInfo = ("dps", "Decoded Per Second");
    pub const BytesPerSec: ProfilerInfo = ("bps", "Bytes Per Second");
}

fn main() {
    for (name, descr) in ALL_VARIABLES.iter() {
        println!("Variable: {}, description: {}", name, descr)
    }
}

Output:

Variable: fps, description: Frames Per Second
Variable: det, description: Decoding Elapsed Time
Variable: dps, description: Decoded Per Second
Variable: bps, description: Bytes Per Second

playground

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know I could match with patterns on macros, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.