Managing Projects with Cargo

Introduction to Cargo

The code execution environment in this course already has all tools installed for us. This includes the Rust compiler. Other than the Rust compiler, Rust ships with a tool named Cargo that assists day-to-day interactions with the language. Cargo handles everything from making projects to fetching packages of premade code. It can run programs and call other tools to fix code formatting and find common errors; Cargo has a tool for everything.

Cargo derives its name from Rust’s structure. Rust programs are called crates, and collections of crates are managed by Cargo. This section walks us through creating our first Rust project and explores what Cargo can do for us.

First, we need to decide where to put our Rust projects.

Selecting a “Home” directory for our code

We may place our projects anywhere we like, but it’s recommended to choose a location that’s easy to find, remember, and type.

If our project directory doesn’t already exist, create it using our regular operating environment tools.

Once we have a home directory selected, we can add a project to it.

Starting a new project with Cargo

Every new project begins as an empty crate. To create a new project:

  1. Open a terminal/command prompt.
  2. Navigate to the home directory we selected for our Rust code (using cd).
  3. Don’t create a new subdirectory for our project, Cargo will do that for us.
  4. Type cargo new [project name].
  5. Rust will have created a subdirectory named [project name]. Enter it with cd [project name].

For example, to make a project named hello in our preferred Rust directory, we’ll use:

Terminal 1
Terminal
Loading...

The created binary (application) hello package has the following directories and files, which can be seen by ls :

  • Cargo.toml: Project meta-data, describing the project.
  • A src directory (containing the source code).
  • src/main.rs: A minimal source code file containing the code required to print “Hello, world!” to the terminal.

cargo new has created a “Hello, world” program.

Let’s take a closer look at what’s happening in the sample program.

You can name your program or crate anything you want. It’s a good idea to use snake_case (words separated with an underscore). If you make a library and name it MyCool-Thing, you’ll have difficulty referencing it in your projects.

Choosing a good name is hard. Don’t worry, you can change it later by editing Cargo.toml. A common quip is that only 2 things are hard in computer science: naming, cache invalidation, and off by one error.

Run Hello, World

We can run the Rust program by using cargo run. Let’s see the following example:

Terminal 1
Terminal
Loading...