从graphql-client转义宏内的关键字

时间:2019-01-07 01:21:25

标签: rust graphql

我正在尝试使用graphql-client板条箱在看起来与此类似的graphql模式上进行请求

enum AttributeType {
    // ...
}

type Attribute {
    name: String!
    type: AttributeType!
}

使用此

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "src/graphql/schema.graphql",
    query_path = "src/graphql/create_something.graphql"
)]
pub struct MutateSomethingModule;

当我尝试使用graphql-client时出现错误:

error: expected identifier, found keyword `type`
  --> src/x/mod.rs:14:10
   |
14 | #[derive(GraphQLQuery)]
   |          ^^^^^^^^^^^^ expected identifier, found keyword
help: you can escape reserved keywords to use them as identifiers
   |
14 | #[derive(r#type)]
   |          ^^^^^^

error: proc-macro derive produced unparseable tokens
  --> src/x/mod.rs:14:10
   |
14 | #[derive(GraphQLQuery)]
   |          ^^^^^^^^^^^^

我猜测此错误消息是在抱怨我有type这个词,因为它是我的架构,应该以某种方式对其进行转义。根据错误消息,我尝试将type:替换为r#type:r#"type"#和其他一些类似的变体。

正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

on the code的基础上,关键字带有下划线:

// List of keywords based on https://doc.rust-lang.org/grammar.html#keywords
let reserved = &[
    "abstract", "alignof", "as", "become", "box", "break", "const", "continue", "crate", "do",
    "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in", "let", "loop",
    "macro", "match", "mod", "move", "mut", "offsetof", "override", "priv", "proc", "pub",
    "pure", "ref", "return", "Self", "self", "sizeof", "static", "struct", "super", "trait",
    "true", "type", "typeof", "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];

if reserved.contains(&field_name) {
    let name_ident = Ident::new(&format!("{}_", field_name), Span::call_site());
    return quote! {
        #description
        #deprecation
        #[serde(rename = #field_name)]
        pub #name_ident: #field_type
    };
}

这意味着type应该以{{1​​}}的身份访问。

另请参阅: