如何使用 println 打印 syn::Expr 的内容?

Sha*_*izi 3 rust

我试图将 a 的内容输出syn::Expr到控制台,但出现以下错误:

error[E0599]: no method named `to_string` found for type `&syn::Expr` in the current scope
   --> derive/src/lib.rs:165:40
    |
165 |                 println!("Expression: {:#?}", expr.to_string());
    |                                                    ^^^^^^^^^
    |
    = note: the method `to_string` exists but the following trait bounds were not satisfied:
            `syn::Expr : std::string::ToString`
            `&syn::Expr : std::string::ToString`
            `syn::Expr : std::string::ToString`
Run Code Online (Sandbox Code Playgroud)

我不清楚什么是“特质界限”或如何满足它们。有什么简单的方法可以输出这个变量的内容吗?

She*_*ter 7

syn::Expr记录为实现Debugtrait,因此您使用Debug格式化程序:

extern crate syn; // 0.15.4

fn example(expr: syn::Expr) {
    println!("{:#?}", expr);
}
Run Code Online (Sandbox Code Playgroud)

但是,所有Debug实现syn都由 Cargo 特性保护extra-traits。因此,为了使用这些Debug实现,您必须在您的Cargo.toml.

[dependencies]
syn = { version = "0.15", features = ["extra-traits"] }
Run Code Online (Sandbox Code Playgroud)

您可以在他们的 README 中阅读更多关于syn可选 Cargo 功能的信息


也可以看看:

  • @ShawnTabrizi 再看看这个答案。我添加了一个关于 `extra-traits` 特性的部分。我希望这有帮助。 (2认同)