“cannot find value `a` in this scope” in Rust macro

一笑奈何 提交于 2021-01-27 17:17:46

问题


I created macro for printing, using proc-macro-hack.
Then this error occured though I already have defined a.

Following is the code.

On decl crate,

proc_macro_expr_decl! {
    /// Function for printing to the standard output.
    ///
    /// First argument can be literal or not literal.
    gprint! => gprint_impl
}

On impl crate,

use syn::{Expr, ExprTuple, parse_str};
use quote::ToTokens;
fn _print_impl(input: &str, print_name: &str) -> String {
    let mut input_with_parens = String::with_capacity(input.len() + 2);
    input_with_parens.push('(');
    input_with_parens.push_str(input);
    input_with_parens.push(')');
    let tuple = parse_str::<ExprTuple>(&input_with_parens)
        .unwrap_or_else(|_| panic!("expected arguments is expressions separated by comma, found {}", input))
    let mut arg_iter = tuple.elems.iter();
    let first = arg_iter.next();
    if first.is_none() {
        return "()".to_string();
    }
    let first = first.unwrap();
    let mut s = String::new();
    if let &Expr::Lit(ref lit) = first {
        s.push_str(print_name);
        s.push('(');
        s.push_str(&lit.into_tokens().to_string());
    } else {
        s.push_str(print_name);
        s.push_str("(\"{}\", ");
        s.push_str(&first.into_tokens().to_string());
    }
    for arg in arg_iter {
        s.push_str(", ");
        s.push_str(&arg.into_tokens().to_string());
    }
    s.push(')');
    s
}

proc_macro_expr_impl! {
    pub fn gprint_impl(input: &str) -> String {
        _print_impl(input, "print!")
    }
}

And tried using this macro,

fn main() {
    let a = 0;
    gprint!(a);
}

error occured:

error[E0425]: cannot find value `a` in this scope

Why?

来源:https://stackoverflow.com/questions/49804878/cannot-find-value-a-in-this-scope-in-rust-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!