Better pattern for optional arguments using repetition in macro by example

⚓ Rust    📅 2025-09-28    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

Hello, everyone!

I want to create macros with optional arguments which will be used to initialize a struct. The pattern that I am using is reproduced below, with the help of optional macro repetitions and shadowing:

#![allow(dead_code)]

#[derive(Debug)]
struct Car {
    name: &'static str,
    max_speed: u32, // km/h
    color: &'static str,
}

macro_rules! new_car {
    ($name:expr $(, max_speed:$max_speed:expr)? $(, color:$color:expr)? ) => {
        {
            // HERE: is there a better pattern?
            let _max_speed = 100; // default
            $(let _max_speed = $max_speed;)?
            let _color = "red"; // default
            $(let _color = $color;)?
            //---------------------------------

            $crate::Car{
                name: $name,
                max_speed:_max_speed,
                color: _color,
            }
        }

    };
}

fn main() {
    println!("{:?}", new_car!("Ferrari"));
    println!("{:?}", new_car!("Lambo1", max_speed: 300));
    println!("{:?}", new_car!("Lambo2", color: "black"));
}

This pattern seems a little bit awkward for me. Do you know any better pattern?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed