Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to idiomatically alias a crate in Rust 2018?

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

like image 285
Tim Diekmann Avatar asked Jun 23 '18 09:06

Tim Diekmann


People also ask

What is extern crate in Rust?

extern crate foo indicates that you want to link against an external library and brings the top-level crate name into scope (equivalent to use foo ). As of Rust 2018, in most cases you won't need to use extern crate anymore because Cargo informs the compiler about what crates are present. (

What is crate root in Rust?

The crate root is a source file that the Rust compiler starts from and makes up the root module of your crate (we'll explain modules in depth in the “Defining Modules to Control Scope and Privacy” section). A package is a bundle of one or more crates that provides a set of functionality. A package contains a Cargo.

Where does Rust store downloaded crates?

registry/src If a downloaded . crate archive is required by a package, it is unpacked into registry/src folder where rustc will find the . rs files.


1 Answers

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" }

WARNING: Cargo prior to Rust 1.26.0 may download the wrong dependency when using this feature!

like image 66
Tim Diekmann Avatar answered Sep 28 '22 12:09

Tim Diekmann