首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >proc_macro上的自我

proc_macro上的自我
EN

Stack Overflow用户
提问于 2022-03-08 15:43:16
回答 1查看 171关注 0票数 0

我正在编写一个过程宏,它接受结构的字段并将它们发送到另一个方法:

代码语言:javascript
复制
pub fn my_helper_macro_builder(macro_data: &MacroTokens) -> TokenStream {
    // Retrieves the fields and tries to add self to take it's value
    let insert_values: Vec<TokenStream> = fields
        .iter()
        .map(|ident| ident.to_string())
        .collect::<Vec<String>>()
        .iter()
        .map(|column| quote! { self.#column })
        .collect();

    quote! {
        #vis async fn insert(&self) {
            <#ty as CrudOperations<#ty>>::__insert(
                #table_name,
                #column_names_pretty,
                &[
                    #(#insert_values),*
                ]
            ).await;
        }
    }
}

当我尝试使用应该在self方法上接收的#vis async fn insert(&self)时,我会收到以下错误:

代码语言:javascript
复制
expected one of `,`, `.`, `;`, `?`, `]`, or an operator, found `"id"

如果我试图将引用宏的签名中可用的&self.连接到quote! {}本身,则会收到以下编译器错误:

代码语言:javascript
复制
   |
8  |   pub fn generate_insert_tokens(macro_data: &MacroTokens) -> TokenStream {
   |          ---------------------- this function can't have a `self` parameter
...
48 | /     quote! {
49 | |         #vis async fn insert(&self) {
50 | |             <#ty as CrudOperations<#ty>>::__insert(
51 | |                 #table_name, 
                       #column_names_pretty, 
                       &[
                            #self.#(#insert_values),*
                        ] 
...  |
57 | |         }
58 | |     }
   | |_____^ `self` value is a keyword only available in methods with a `self` parameter
   |
   = note: this error originates in the macro `$crate::quote_token_with_context` 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-08 17:31:27

正如@Shepmaster所指出的,问题是,我是在串列的名称,所以最后的代码如下所示:

代码语言:javascript
复制
pub fn my_helper_macro_builder(macro_data: &MacroTokens) -> TokenStream {
    // Retrieves the fields and tries to add self to take it's value
    let insert_values = fields.iter().map( |ident| {
        quote! { &self.#ident }
    });

    quote! {
        #vis async fn insert(&self) {
            <#ty as CrudOperations<#ty>>::__insert(
                #table_name,
                #column_names_pretty,
                &[
                    #(#insert_values),*
                ]
            ).await;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71397717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档