Using values for a macro_rules! macro

I am using a macro in order to prevent from repeating a large code block.
However, to generate the values for the macro, I currently set variables for the sole reason to make the compiler happy, they are not used by the macro:

pub async fn cpu_statistics(cpu_data: CpuStat, timestamp: DateTime<Local>, statistics: &mut HashMap<(String, String), Statistic>)

    let (user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    macro_rules! add_cpu_data_field_to_statistics {
        ($($field_name:ident),*) => {
                statistics.entry((, stringify!($field_name).to_string()))
                .and_modify(|row| {
                    row.delta_value = cpu_data.$field_name as f64 - row.last_value;
                    row.per_second_value = row.delta_value / (timestamp.signed_duration_since(row.last_timestamp).num_milliseconds() as f64 / 1000_f64);
                    row.last_value = cpu_data.$field_name as f64;
                    row.last_timestamp = timestamp;
                    row.new_value = false;
                    Statistic {
                        last_timestamp: timestamp,
                        last_value: cpu_data.$field_name as f64,
                        delta_value: 0.0,
                        per_second_value: 0.0,
                        new_value: true,
    add_cpu_data_field_to_statistics!(user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice);

The aim for the macro is to go through the fields of user, nice, system, etc. in the CpuStat struct, and add them to the statistics hash map, or change the values (entry().and_modify().or_insert()).

I do understand that the values for fields have to be provided to the macro in this way, because of how macro's work.

Is there a better and more beautiful way of doing this?

What's the exact error message? Because you shouldn't have to declare any variables in order to pass the macro your identifiers.

1 Like