Hello, Cargo!

Cargo is Rust’s build system and package manager.

Create a new project

To create a new project using Cargo

$ cargo new hello_cargo

Cargo defaults to --bin to make a binary program. To make a library, we’d pass --lib.


Cargo.toml is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format.

name = "hello_cargo"
version = "0.1.0"
authors = ["ky"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html


This is called a manifest, and it contains all of the metadata that Cargo needs to compile the package.

The first line, [package], is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections.

The next four lines set the configuration information Cargo needs to compile your program: the name, the version, who wrote it, and the edition of Rust to use. Cargo gets your name and email information from your environment, so if that information is not correct, fix the information now and then save the file. We’ll talk about the edition key in Appendix E.

The last line, [dependencies], is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as crates. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then.



Cargo has generated a “Hello, world!” program.

fn main() {
    println!("Hello, world!");

Building and Running a Cargo Project

To build the project:

$ cargo build

The executable file, target/debug/hello_cargo, is created.

We can also use cargo run to compile the code and then run the resulting executable all in one command:

$ cargo run

cargo check command quickly checks our code to make sure it compiles but doesn’t produce an executable:

$ cargo check

Why would you not want an executable? Often, cargo check is much faster than cargo build, because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using cargo check will speed up the process! As such, many Rustaceans run cargo check periodically as they write their program to make sure it compiles. Then they run cargo build when they’re ready to use the executable.


Building for Release

When the project is finally ready for release, cargo build --release is the script to compile it with optimizations. 

$ cargo build --release

The executable is created in target/release.

Leave a Comment

Your email address will not be published. Required fields are marked *