0

How to use Local Unpublished Crates

Last Updated on

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

A Local Unpublished Crate

I 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 I am using a dash in the name. When referring to the crate in Rust codes, replace the dashes with underscores.

lib.rs

Essentially, I 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 above-mentioned crate and uses its lone function. I 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 I used turreta_create instead of turreta-crate? Otherwise, my codes won’t be able to find my crate.

Output:

Tested with Rust 1.40.0.

References

Karl San Gabriel

Karl San Gabriel

Professional Software Developer