Sub topic 5
Creating your first project with cargo new
This chapter covers cargo new, the command that creates a Rust project. It assumes the following:
- You have installed Rust with rustup and confirmed that
rustc --versionandcargo --versionwork. - You are comfortable running commands in a terminal.
- You know roughly what a compiler and a package manager do.
The next chapters go through each generated file and each build command in detail. Here the focus is the command itself: what it creates, which options change the result, and what the common errors mean.
What cargo new does
cargo new makes a directory and fills it with a minimal Cargo package. A package is the unit Cargo builds. It has a manifest file, Cargo.toml, and source code that compiles into one or more crates. A crate is a single compilation unit, either a runnable program (a binary crate) or a reusable library (a library crate).
The simplest form takes a name:
cargo new hello_cargo
cd hello_cargo
cargo runCargo prints a line such as Creating binary (application) package, followed by a note about Cargo.toml keys. The exact wording differs between Cargo versions. Then cargo run compiles the project and runs it. The program prints Hello, world!.
The generated src/main.rs looks like this:
fn main() {
println!("Hello, world!");
}main is the entry point of a binary crate. When you run the compiled program, execution starts at this function.
What gets created
For a binary project, cargo new hello_cargo produces this tree:
hello_cargo/
├── .gitignore
├── Cargo.toml
└── src/
└── main.rsThree details matter at this stage:
- The new directory has the name you gave. Cargo uses the same string as the package name inside
Cargo.toml. - Cargo creates a Git repository in the directory and writes a
.gitignorefile that excludestarget/. This is the folder where build output goes. It does not exist yet, because nothing has been built. - There is no
Cargo.lockyet. Cargo creates it on the first build or run.
The files are covered in depth in the next chapter. For now, check that Cargo.toml starts with a [package] table that has your name, a version, and an edition.
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]The edition value depends on your Cargo version. A newer Cargo may write a newer edition than the 2021 shown here. An edition is an opt-in set of language changes that lets Rust evolve without breaking existing code.
Binary or library
cargo new makes a binary by default. You choose a library with a flag.
| Command | Result | Entry file | Typical use |
|---|---|---|---|
| `cargo new app` | Binary crate | `src/main.rs` | A program you run |
| `cargo new app --bin` | Binary crate (explicit) | `src/main.rs` | Same as the default |
| `cargo new mylib --lib` | Library crate | `src/lib.rs` | Code other crates call |
A library has no main function and cannot be run. cargo run fails on a library-only package. You exercise a library through tests, or by depending on it from another crate.
cargo new mylib --libThe generated src/lib.rs contains a small function and a test module. The exact contents differ between Cargo versions. One common version is:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5);
}
}Running cargo test inside the library directory compiles this file in test mode and runs the marked function. The later chapter on library crates and tests covers this in more detail.
A package can hold both a library and a binary. If you add a src/main.rs to a library package, Cargo builds both, and the binary can use the library. You do this by creating the file yourself. cargo new does not generate both at once.
Useful options
cargo new accepts several flags. These are the ones you will use most.
Version control
By default Cargo runs git init. It skips this step if the new directory is already inside a Git repository. Use --vcs to change the behavior:
cargo new scratch --vcs noneThe accepted values are git, hg, pijul, fossil, and none. Choose none for throwaway experiments or when you plan to place the project inside a larger repository you manage yourself.
Edition
--edition sets the edition written to Cargo.toml:
cargo new legacy_tool --edition 2021Use this when a project must match the edition of existing code. Otherwise accept the default, which is the newest edition your Cargo version supports.
Package name
--name sets the package name independently of the directory name:
cargo new app_dir --name my_appThis creates a directory called app_dir whose package is named my_app. It is rarely needed. Most of the time, choose a good directory name and let Cargo reuse it.
Naming rules
The name you pass becomes the package name, and Cargo checks it. These rules catch most problems:
- The name must not start with a digit.
cargo new 2fastfails. - It may contain letters, digits,
-, and_. Other characters are rejected. - It must not be a Rust keyword such as
fnormatch. - It must not collide with names the compiler reserves. For example,
testis refused because it conflicts with Rust's built-in test library.
Hyphens deserve extra attention. A package named hello-world is valid. But in Rust source code, the crate is referred to as hello_world, because Rust identifiers cannot contain hyphens. Cargo converts hyphens to underscores for you. This is why many published crates have a hyphenated package name and an underscored import name.
cargo init for an existing directory
cargo new refuses to run if the target directory exists:
error: destination `/home/you/hello_cargo` already exists
Use `cargo init` to initialize the directorycargo init does the same work inside a directory that is already there. It takes the same flags, and it uses the current directory name as the package name unless you give --name.
mkdir notes_cli
cd notes_cli
cargo initUse cargo init when you have already created the directory, for example by cloning an empty repository. cargo init also keeps existing files. If it finds a file such as src/main.rs, it does not overwrite it. If a .gitignore already exists, Cargo appends the entries it needs.
Creating a project inside a workspace
A workspace is a set of packages that share one Cargo.lock and one target directory. If you run cargo new inside a directory tree that has a workspace root, Cargo notices it. It adds the new package to the members list in the workspace's Cargo.toml. This is useful in larger projects. It can also surprise you if you create a scratch project inside a workspace by accident. Check the parent Cargo.toml if a new project does not behave like a standalone one.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `destination ... already exists` | The directory is already there | Use `cargo init`, or pick a different name |
| `invalid character` or `cannot start with a digit` in the name message | The name breaks the naming rules | Rename, for example `app2` instead of `2app` |
| `command not found: cargo` | Cargo's bin directory is missing from `PATH` | Open a new terminal, or add `~/.cargo/bin` to `PATH` |
| `cargo run` says there is no binary target | The project was created with `--lib` | Add `src/main.rs`, or use `cargo test` |
| `linker 'cc' not found` on first build | A C linker is not installed | Install your platform's build tools |
The last two installation errors belong to the troubleshooting chapter, which explains them fully. They appear here because a first cargo run is often when they surface.
A short checklist for a new project
After cargo new, do these steps in order:
- Run
cargo runfor a binary, orcargo testfor a library. A successful result shows the toolchain works end to end. - Open
Cargo.tomland confirm the name, version, and edition. - Read the generated
srcfile so you know where your code begins. - Make a first commit if you are using version control. The
.gitignorealready keepstarget/out of it.
Exercise
You run cargo new 3d_viewer and Cargo rejects the name. What is wrong, and what is one command that gives you a project in a directory called viewer_3d?
Show answer
A package name cannot start with a digit, so 3d_viewer is invalid. Run cargo new viewer_3d. The name starts with a letter, so Cargo accepts it.
Exercise
A directory called tools already exists and is empty. Which command turns it into a library project, and which flag makes the project a library?
Show answer
Run cargo init --lib inside the tools directory. The --lib flag selects a library crate, which gets src/lib.rs instead of src/main.rs. cargo new would fail here because the directory already exists.
Exercise
You create a package named text-tools. How do you refer to its crate in Rust source code, and why?
Show answer
You write text_tools. Rust identifiers cannot contain hyphens, so Cargo converts hyphens in the package name to underscores for the crate name.