A macro where an argument that may have a comma

I have a type GAD<F, U> that functions like the floating point type F .

I wish to write a macro where one of its arguments could be a valid choice for F (e.g.,. f64 ) or a valid choice for GAD<F,U> (e.g. GAD<f64,u32> ).

How does one create a macro pattern so that one of the arguments could be f64 or GAD<f64,u32> ?

If you're not trying to branch on those two cases in the macro or the like, you can use the ty fragment specifier.

macro_rules! they_are_both_types_so {
    ($you_can_match_on_a_ty_fragment:ty) => {
        std::any::type_name::<$you_can_match_on_a_ty_fragment>()
    }
}

// ...
println!("{}", they_are_both_types_so!(f64));
println!("{}", they_are_both_types_so!(Gad<f64, u32>));
1 Like

The following worked for me:

truct Gad<F,U> {
    f : F,
    u : U,
}
macro_rules! macro_with_ty_argument {
    ($T:ty) => {
        std::any::type_name::< $T >()
    }
}
// 
fn main()
{   println!("{}", macro_with_ty_argument!(f64));
    println!("{}", macro_with_ty_argument!(Gad<f64, u32>));
    //
    // use Gad fields to avoid a warning.
    let gad : Gad<f32, u64> = Gad{ f : 1.0,  u : 2 };
    println!("{}, {}", gad.f, gad.u);
   
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.