How to idiomatically alias a crate in Rust 2018?

2019-01-20 09:48发布

I have a crate foo_sys. In Rust 2015 I used extern crate foo_sys as foo for convenience, but in Rust 2018 extern crate isn't needed anymore and I don't want to use it only for aliasing. When dropping extern crate, I get

error[E0463]: can't find crate for foo

2条回答
相关推荐>>
2楼-- · 2019-01-20 10:20

The idiomatic solution is to rename the crate in Cargo.toml. See the answer by Tim Diekmann for more information about that.

But if you don't want to use Cargo.toml renaming for some reason, you can still use the old syntax. It's soft-deprecated, but not removed. So this still works:

extern crate foo_sys as foo;

(Playground example)

查看更多
太酷不给撩
3楼-- · 2019-01-20 10:23

This can be achieved with the rename-dependency Cargo feature, available in Rust 1.31. With this feature, it's possible to provide a package attribute to the dependencies:

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.

Instead of writing

[dependencies]
foo_sys = "0.2"

the package key can be added to the dependency in Cargo.toml:

[dependencies]
foo = { package = "foo_sys", version = "0.2" }
查看更多
登录 后发表回答