Bitterless Rust

Getting Started with Cargo

What Is Cargo

Cargo is Rust's build tool and package manager. Think of it like npm for JavaScript, or pip + venv for Python. If you're writing Rust, you use Cargo. That's all you need to know.

Creating a Project

cargo new hello-rust

This creates a directory called hello-rust. Here's what's inside:

hello-rust/
├── Cargo.toml
└── src/
    └── main.rs

Just 2 files. Simple.

Cargo.toml

[package]
name = "hello-rust"
version = "0.1.0"
edition = "2021"

[dependencies]

[package] is the project info. [dependencies] is where you list external libraries (crates). It's empty for now.

Oversimplification warning: edition is like a Rust "year version." Don't think too hard about it. Just leave it at 2021.

main.rs

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

fn main() is the program's entry point. println! prints a string. The ! at the end means it's a macro, but for now just remember "println needs a !."

Building and Running

cd hello-rust
cargo run

Output:

   Compiling hello-rust v0.1.0 (/path/to/hello-rust)
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
     Running `target/debug/hello-rust`
Hello, world!

cargo run builds and runs in one shot.

Other useful commands to remember:

Command What it does
cargo run Build and run
cargo build Build only
cargo check Check if it compiles (no build. Fast)

For everyday development, cargo run and cargo check are all you need.

Adding External Crates

You won't need this in later chapters, but good to know. To add an external library:

cargo add serde

This automatically adds it to [dependencies] in Cargo.toml:

[dependencies]
serde = "1.0"

You can find available crates at crates.io. Think of it like npm.


That's the basics of Cargo. Next, let's start writing Rust code.

Related

Back to book