[英]How can I get “Bar” from “Foo::Bar” in rust macro?
Original demand: I want to implement a macro that converts Foo::*
to Bar::*
.原始需求:我想实现一个将Foo::*
转换为Bar::*
的宏。
Pseudo code will look like this:伪代码将如下所示:
macro_rules! convert_foo_to_bar {
($v: ty, $p: path) => (<$v>::$p.name)
}
// convert_foo_to_bar!(Bar, Foo::A) -> Bar::A
While $p.name
refers to A
.而$p.name
指的是A
。
You can match the Foo::A
using Foo::$variant:ident
to get A
as $variant
like this:您可以使用Foo::$variant:ident
匹配Foo::A
以获得A
作为$variant
,如下所示:
macro_rules! convert_foo_to_bar {
($v: ty, Foo::$variant:ident) => (<$v>::$variant)
}
If you need to convert a variable, you will need to use a normal function such as this:如果需要转换变量,则需要使用普通的 function,例如:
fn convert_foo_to_bar(foo: Foo) -> Bar {
match foo {
Foo::A => Bar::A,
Foo::B => Bar::B,
// .. for all of your variants
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.