如何使用宏将元组扩展为其成员作为函数参数?

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

我有一个来自外部库 [1] 的函数,例如

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

我想在像

这样的元组中管理我的颜色
let yellow = (1., 1., 0.);

我想到了这样一个宏:

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

playground

然后

set_color(rgb!(yellow));

不幸的是 Rust 然后说:error: macro expansion ignores token ',' and any following.

我怎样才能做到这一点?


[1]: cairo::Context::set_source_rgb() 和朋友

你不能这样做。 Rust 宏不是执行愚蠢文本操作的 C 宏; Rust 宏必须生成有效的 Rust 代码,a, b, c 无效。

最接近的方法是将函数传递给宏:

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