Rust has an official package manager that most Rust programmers, so-called “Rustaceans”, called Cargo. Cargo’s features include simplifying the creation of your projects, managing their dependencies and compiling and running your projects to name a few.
If you followed along with Rust - First Steps you should have Cargo installed.
You can check this with:
|
|
And should get something like:
|
|
Creating a project
To create a project navigate over to the directory where you keep your coding projects. To create a project called hello_world_cargo
run the following:
|
|
Remember that the typical naming convention for Rust files is to use underscores in the place of spaces (snakecase)
If all goes well you should see the following:
|
|
And you should see the following directories and files:
|
|
Cargo.toml
Cargo uses the TOML file format to manage the project’s config. Below is our Cargo.toml
with some useful comments:
|
|
src/main.rs
If you’ve been following along from Rust - First Steps src/main.rs
should look familiar - it simply prints out “Hello, World!” to standard output.
Building and running the project
Building the project is as simple as running:
|
|
If the projects builds successfully you can expect the following output:
|
|
By default, Cargo creates a debug build and outputs the program binary to target/debug
. This can now be run with:
|
|
After the first build with Cargo, a Cargo.lock
file is created which keeps track of the exact dependencies and their versions as they pertain to your project.
You can build and run the project at the same time with Cargo’s run
command thusly:
|
|
Checking your code before building and running
Cargo allows you to check your code for any issues that would cause your it not to compile. check
doesn’t produce a binary and therefore executes quicker than the build
and run
commands. For this reason many Rust developers run it often while coding.
|
|
Building for release
When you’re sure that your code is spick-and-span and ready to be released into the wild, run:
|
|
Not only does Cargo now place the binary into target/release
, but more importantly, Cargo optimises your code in order to make your Rust run quicker. This does come with a compilation speed knock which is why there is a faster compilation version i.e. debug, for when you’re in the midst of coding.
Remember to use the release version of your program when doing any kind of benchmarking.
peace___ c", )