如何在 Rust 2018 中惯用地为箱子起别名?
How to idiomatically alias a crate in Rust 2018?
我有一个板条箱foo_sys
。在 Rust 2015 中,为了方便起见,我使用 extern crate foo_sys as foo
,但在 Rust 2018 中,不再需要 extern crate
,我不想仅将其用于别名。删除 extern crate
时,我得到
error[E0463]: can't find crate for foo
惯用的解决方案是重命名 Cargo.toml
中的板条箱。有关详细信息,请参阅 。
但如果您出于某种原因不想使用 Cargo.toml
重命名,您仍然可以使用旧语法。它已被软弃用,但未被删除。所以这仍然有效:
extern crate foo_sys as foo;
这可以通过 rename-dependency Cargo feature, available in Rust 1.31 实现。使用此功能,可以为依赖项提供包属性:
The rename-dependency feature allows you to import a dependency with a different name from the source. This can be useful in a few scenarios:
- Depending on crates with the same name from different registries.
- Depending on multiple versions of a crate.
- Avoid needing
extern crate foo as bar
in Rust source.
而不是写作
[dependencies]
foo_sys = "0.2"
package
键可以添加到Cargo.toml
中的依赖:
[dependencies]
foo = { package = "foo_sys", version = "0.2" }
警告:Cargo prior to Rust 1.26.0 may download the wrong dependency 使用此功能时!
我有一个板条箱foo_sys
。在 Rust 2015 中,为了方便起见,我使用 extern crate foo_sys as foo
,但在 Rust 2018 中,不再需要 extern crate
,我不想仅将其用于别名。删除 extern crate
时,我得到
error[E0463]: can't find crate for
foo
惯用的解决方案是重命名 Cargo.toml
中的板条箱。有关详细信息,请参阅
但如果您出于某种原因不想使用 Cargo.toml
重命名,您仍然可以使用旧语法。它已被软弃用,但未被删除。所以这仍然有效:
extern crate foo_sys as foo;
这可以通过 rename-dependency Cargo feature, available in Rust 1.31 实现。使用此功能,可以为依赖项提供包属性:
The rename-dependency feature allows you to import a dependency with a different name from the source. This can be useful in a few scenarios:
- Depending on crates with the same name from different registries.
- Depending on multiple versions of a crate.
- Avoid needing
extern crate foo as bar
in Rust source.
而不是写作
[dependencies]
foo_sys = "0.2"
package
键可以添加到Cargo.toml
中的依赖:
[dependencies]
foo = { package = "foo_sys", version = "0.2" }
警告:Cargo prior to Rust 1.26.0 may download the wrong dependency 使用此功能时!