First Steps with Cargo
This section provides a quick sense for the cargo
command line tool. We
demonstrate its ability to generate a new package for us,
its ability to compile the crate within the package, and
its ability to run the resulting program.
To start a new package with Cargo, use cargo new
:
$ cargo new hello_world
Cargo defaults to --bin
to make a binary program. To make a library, we
would pass --lib
, instead.
Let’s check out what Cargo has generated for us:
$ cd hello_world
$ tree .
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
This is all we need to get started. First, let’s check out Cargo.toml
:
[package]
name = "hello_world"
version = "0.1.0"
edition = "2024"
[dependencies]
This is called a manifest, and it contains all of the metadata that Cargo needs to compile your package.
Here’s what’s in src/main.rs
:
fn main() { println!("Hello, world!"); }
Cargo generated a “hello world” program for us, otherwise known as a binary crate. Let’s compile it:
$ cargo build
Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
And then run it:
$ ./target/debug/hello_world
Hello, world!
We can also use cargo run
to compile and then run it, all in one step:
$ cargo run
Fresh hello_world v0.1.0 (file:///path/to/package/hello_world)
Running `target/hello_world`
Hello, world!
Going further
For more details on using Cargo, check out the Cargo Guide