1

该宏在调用时编译:

macro_rules! remote_optional {
    ($remote:ident with=$def:ident $def_str:expr) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = $def_str)] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    }
}

这个没有:

macro_rules! remote_optional {
    ($remote:ident with=$def:ident) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = stringify!($def))] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    }
}

这是因为stringify!($def)被传递到未评估的#[serde(...)]属性中。

有什么实用的解决方法吗?

4

1 回答 1

2

两个参数的宏可以转发到三个参数的宏,扩展def标识符吗?

macro_rules! remote_optional {
    // The one that doesn't work (two arguments)
    // forwards to the one that *does* work, expanding the
    // string.
    ($remote:ident with=$def:ident) => {
        remote_optional!($remote, with=$def, stringify!($def));
    };

    // The macro that *does* work
    ($remote:ident with=$def:ident $def_str:expr) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = $def_str)] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    };
}

我们还可以考虑将三个参数的宏作为实现细节。

小的、孤立的概念验证:

macro_rules! my_macro {
    ($x:expr, $y:expr) => {
        my_macro!($x, $y, stringify!($x + $y));
    };

    ($x:expr, $y:expr, $msg:expr) => {
        println!("{} + {} = {}", $x, $y, $msg);
    };
}


fn main() {
    my_macro!(3, 2); // 3 + 2 = 3 + 2
}
于 2019-04-09T00:42:09.820 回答