Rust 预期枚举 `syn::UseTree`,找到结构 `syn::Path`

Rust expected enum `syn::UseTree`, found struct `syn::Path`

我是 Rust 的新手,正在尝试弄清楚如何进入发现 syn 返回的这个 AST 结构的工作流程。

[package]
name = "rust-ast"
version = "0.1.0"
authors = ["Foo Bar <foo@bar.com>"]
edition = "2018"

[dependencies]
syn = { version = "1.0.89", features = ["full", "printing", "visit", "extra-traits"] }

即Cargo.toml,这里是主文件:

use syn;

use std::env;
use std::fs::File;
use std::io::Read;
use std::process;

fn main() {
  let mut args = env::args();
  let _ = args.next(); // executable name

  let filename = match (args.next(), args.next()) {
    (Some(filename), None) => filename,
    _ => {
      eprintln!("Usage: dump-syntax path/to/filename.rs");
      process::exit(1);
    }
  };

  let mut file = File::open(&filename).expect("Unable to open file");

  let mut src = String::new();
  file.read_to_string(&mut src).expect("Unable to read file");

  let syntax = syn::parse_file(&src).expect("Unable to parse file");

  let mut str = String::from("");

  for item in syntax.items {
    match item {
      syn::Item::Use(x) => {
        match x.tree {
          syn::path::Path { .. } => {
            println!("{:#?}", x);
          },

        }
        str.push_str("load");
      },
      _ => println!("Skip")
    }
  }
  // let iterator = syntax.iter();
  // for val in iterator {
  //   println!("Got: {:#?}", val);
  // }
}

我能够更早地打印出 x,其中显示:

但是,我现在收到这个错误:

this expression has type `syn::UseTree`
expected enum `syn::UseTree`, found struct `syn::Path`

首先,如何发现VSCode中的API?我已经启用了 rust 插件,所以我可以点击 some 定义,但我查看了 AST“类型”的终端输出,然后我尝试向后找出类型是什么在 VSCode。通常我求助于在 docs page 上查找它,但是有关如何弄清楚 API 应该是什么的任何提示都将帮助我学会钓鱼。但是对于这个特定的问题,我做错了什么?我只是想尽可能多地将 AST 解构到叶子,以便更熟悉 Rust(我才刚刚开始)。

But for this particular question, what am I doing wrong?

x.tree 属于 UseTree 类型,它是一个枚举:

pub enum UseTree {
    Path(UsePath),
    Name(UseName),
    ... other variants snipped ...
}

因此您需要匹配 UseTreePath 变体:

match x.tree {
    UseTree::Path { .. } => { ... },
    _ => todo!(),
}

First of all, how do I discover the API in VSCode?

我不使用 VS 代码,但我发现单击对 Rust 和 stdlib 效果很好,而对宏繁重的库(例如 syn)效果不佳。幸运的是 syndocumentation 真的很好。

am simply trying to destructure the AST as much as possible down to the leaves, to get more familiar with Rust (I am just beginning).

syn 可能非常复杂,因此我不建议将此作为学习语言的方法。