Rust Crates!
Similar to Perl-CPAN
, R-CRAN
, Python-Pypi
, Java-Maven
, Rust
has crates.io
, where one can publish the code for others to utilize the functionality. In this post, let’s explore,
- Using one such publicly available crate,
rand
. - Rust Modules.
- Rust Crates.
- Publishing our own crate,
movies
.
Let’s get started!
-
Using rand crate.
If you want to follow along and bring up
Rust
environment locally, please feel free to clonemy github repo
andcompose up
using,
Now you are on Rust
docker container and ready to code along …
Time to add rand
crate to project dependency list.
Add the following to Cargo.toml
file.
Running cargo run
will fetch rand crate
as showed in the output below.
Updating crates.io index
Downloaded cfg-if v1.0.0
Downloaded rand v0.8.5
...
Running `target/debug/movie-crate-demo`
Hello, world!
Add the following to src/main.rs
file.
Output:
1) +18
2) -33
3) -28
...
9) -74
10) -109
-
Rust Modules.
Let’s create a module movies
and add a function play
that prints a movie name that we pass to this function.
Create a file src/movie.rs
with following content.
It’s time to include this module in our Cargo.toml
.
[lib]
name = "movies"
path = "src/movies.rs"
Now, let’s test our movies module
by adding following code to our src/main.rs
file.
Output:
Playing movie: Good Will Hunting
-
Rust Crates.
From within the folder, movie-crate-demo
, run the following to create movies crate
and move exising movies module
into movies crate
.
cargo new --lib movies
mv src/movies.rs movies/src/
Remove the following content from movie-crate-demo/Cargo.toml
and in turn add this content to movie-crate-demo/movies/Cargo.toml
.
[lib]
name = "movies"
path = "src/movies.rs"
Add the following to movie-crate-demo/Cargo.toml
file.
[dependencies]
movies = { path = "movies" }
Edit movie-crate-demo/src/main.rs
file with the following,
Output:
Playing movie: Good Will Hunting
-
Publishing Movies Crate to crates.io
In order to publish crates, you need to create an account on crates.io. Run the following to publish our movies crate
to crates.io.
cd movies
cargo login <api-token>
cargo package --allow-dirty
cargo publish --allow-dirty
That’s it. You now have your movies crate
published onto crates.io. Here’s how it looks after I published my movies crate
.
-
Using our published Movies Crate in our project.
Edit the
movie-crate-demo/Cargo.toml
as follows,
Running cargo run
will download movies crate
from crates.io
and will output,
Playing movie: Good Will Hunting
To recap, we explored,
- Using
rand
crate. - Created
movies
module. - Created
movies
crate. - Published
movies crate
tocrates.io
. - Used
movies crate
in our project.
Happy Publishing Rust Crates
!!