Rust, Software Development

How to use Local Unpublished Crates

At some point in learning Rust, we will need to create crates, but these go through development and testing before we publish them to creates.io. This brief post is about creating and using local unpublished crates.

A Local Unpublished Crate

We have this unpublished crate called turreta_crate, and it resides in c:\rust\turreta-crate. It is a simple crate with one public function.

Cargo.toml

This file is as-is. Note here that we are using dashes in the name. When referring to the crate in Rust codes, replace the dashes with underscores.

lib.rs

Essentially, we have a crate with a single public function that displays a greeting message on the command-line console. Nothing special!

A Local Application

This application references the crate mentioned above and uses its lone function. We could also create another crate doing the same thing.

Cargo.toml

The only changes here are the last two lines. One is a comment line, and the other is a reference to the local unpublished crate. The path can be either be an absolute or a relative path relative to the current project.

It is possible to use wildcards for version, but that wouldn’t be a sound choice, particularly for cases where we work on various versions of a crate.

main.rs

From here on, everything is the same as how we would typically import and use libraries in Rust – use extern crate <CREATE_NAME>  and use to reference specific codes. Local unpublished crates are the same as the publicly published ones.

To link a crate to this new library, the extern crate declaration must be used. This will not only link the library, but also import all its items under a module named the same as the library. The visibility rules that apply to modules also apply to libraries.

Notice we used turreta_create instead of turreta-crate? Otherwise, our codes won’t be able to find my crate.

Output:

Tested with Rust 1.40.0.

References

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like