How do I use a macro to expand a tuple to its members as function arguments?

Viewed 712

I have a function from an external library [1] like

fn set_color(r: f64, g: f64:, b: f64)

I would like to manage my colors in tuples like

let yellow = (1., 1., 0.);

I thought of a macro like:

macro_rules! rgb {
    ( $rgb:expr ) => { rgb.0, rgb.1, rgb.2 }
}

playground

and then

set_color(rgb!(yellow));

Unfortunately Rust then says: error: macro expansion ignores token ',' and any following.

How can I make this happen?


[1]: cairo::Context::set_source_rgb() and friends

1 Answers

You cannot do this. Rust macros are not C macros that perform dumb textual manipulation; Rust macros must result in valid Rust code and a, b, c is not valid.

The closest would be to pass in the function to the macro:

macro_rules! rgb {
    ($f:expr, $rgb:expr) => {
        $f($rgb.0, $rgb.1, $rgb.2)
    };
}
let white = (1., 1., 1.);
rgb!(set_color, white);
Related