简体   繁体   English

如何使用 Vec 消除类型歧义<t>在 Rust 的 macro_rules 中?</t>

[英]How to disambiguate against types with Vec<T> in macro_rules in Rust?

Let's say I have假设我有

macro_rules! tipey {
    (Vec<$pt: ty>) => {2};
    ($pt: ty) => {1};
}

macro_rules! structy {
    (struct $i: ident { $($p: ident : $(Vec<)? $pt: ty $(>)?,)+ }) => {
        const v: &[usize] = &[ $(tipey!($pt)),+ ];
    };
}

structy!(
    struct ContentDetails {
        pattern: String,
        fields: Vec<String>,
    }
);

I want to somehow be able to disambiguate the type and know whether it is a Vec<> or a simple type.我想以某种方式能够消除类型的歧义,并知道它是Vec<>还是简单类型。 I'm only dealing with Vecs so no need to expand if not possible.我只处理 Vecs,所以如果不可能的话不需要扩展。

The issue I have is that if I match Vec<bool> against just $t: ty then I cannot split it up later to see if the $t was Vec<> or not but if I try to collect multiple tt s or something else then parsing the list of properties breaks.我遇到的问题是,如果我将Vec<bool>$t: ty匹配,那么我以后无法将其拆分以查看$t是否为Vec<>但如果我尝试收集多个tt或其他内容然后解析属性列表。 I really want to avoid having to use proc macros我真的想避免使用 proc 宏

This is going to be very unreliable for general types, and generic Rust syntax.对于一般类型和通用 Rust 语法,这将是非常不可靠的。 But if you have a very narrow use-case then you can fix up your code something like this:但是如果你有一个非常狭窄的用例,那么你可以像这样修复你的代码:

macro_rules! tipey {
    (Vec<$pt: tt>) => { 2 };
    ($pt: tt) => { 1 };
}

macro_rules! structy {
    (struct $i: ident { 
        $($p: ident: $pt: tt $(<$gt: tt>)?),+
        $(,)?
    }) => {
        const v: &[usize] = &[ $(tipey!( $pt $(<$gt>)?)),+ ];
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM