查看 crates 提供哪些 features

691 阅读1分钟

背景

在 rust 开发中, 我们经常需要使用一些 crates, 所以在我们添加 crate 的时候,默认会使用 default 的 feature,

cargo add serde

# 通过命令添加完依赖之后, Cargo.toml 文件的依赖会新增对应的依赖,但是但是没有指定 feature
serde = "1.0.196"
# 在使用的时候, 可能会遇到以下或者类似的问题
cannot find derive macro Deserializ in this scope
error: cannot find derive macro `Serialize` in this scope
 --> common/src/result.rs:2:10
  |
2 | #[derive(Serialize,Deserializ)]
  |          ^^^^^^^^^

error: cannot find derive macro `Deserializ` in this scope
 --> common/src/result.rs:2:20
  |
2 | #[derive(Serialize,Deserializ)] 

也可以使用, 通过 --features 来指定 feature, 下面的样例表示使用最新版本的 serde并且使用 derive 这个feature

cargo add serde --features derive

如何查看对应的 crate 提供了哪些 features呢?

  1. docs.rs 在对应的 crate 页面上提供了 Features flags 对应的跳转页面

image-20240216104938797.png

  1. 通过命令行添加 crate 时,命令行回显

    cargo add axum-valid  
        Updating `sjtu` index
          Adding axum-valid v0.15.0 to dependencies.
                 Features:
                 + basic
                 + form
                 + json
                 + query
                 + validator
    

参考

  1. [查看 Rust Crates 的 Features](www.jtr109.com/posts/crate…)