Use quote in a match statement

Is there a way to use Quote on the left side of a match expression as such?

fn to_string(ty: &syn::TokenStream) -> &'static str
    match ty
        quote!(f32) => "f32",
        quote!([f32; 2]) => "f32x2",  
        _ => panic!("unexpected"),

You cannot use quote! directly as match patterns (unless you store each variant within its own constant, which requires quote! to be const-able and with many branches it wouldn't be the most efficient).

So the best thing in this case is to use a map, such as a HashMap, using syn::Type as key, provided the "extra-traits" feature is enabled (to ensure syn types are Hash + Eq, which TokenStream never is):

fn to_string (ty: TokenStream) -> &'static str
    type Map = ::std::collections::HashMap<::syn::Type, &'static str>;
    thread_local! {
        static MAP: Map = {
            let mut map = Map::with_capacity(2);
            let _ = map.insert(::syn::parse_quote!(f32), "f32");
            let _ = map.insert(::syn::parse_quote!([f32; 2]), "f32x2");
    let ty: ::syn::Type = ::syn::parse(ty).unwrap();
    MAP.with(|it| {
        it  .get(&ty)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.