Sub topic 6
What Cargo generates
This chapter assumes you have installed Rust with rustup, can run rustc --version and cargo --version, and have run cargo new at least once. It covers what cargo new creates, what cargo build adds later, and which of those files you edit, commit, or ignore.
What `cargo new` creates
Running cargo new hello_cargo makes a directory with this layout:
cargo new hello_cargo
cd hello_cargo
find . -path ./.git -prune -o -type f -printThe output lists three files:
./Cargo.toml
./src/main.rs
./.gitignoreCargo also runs git init in the new directory and creates a .git directory, unless the directory is already inside a Git repository. The .git directory is pruned from the listing above.
| Path | Created by | You edit it? | Commit it? |
|---|---|---|---|
| `Cargo.toml` | `cargo new` | Yes | Yes |
| `src/main.rs` | `cargo new` | Yes | Yes |
| `.gitignore` | `cargo new` | Rarely | Yes |
| `Cargo.lock` | First build or `cargo check` | No, Cargo manages it | Yes for applications |
| `target/` | First build or `cargo check` | No | No |
The next sections look at each of these in turn.
The source directory
Cargo expects your code in src. The top level of the project holds everything else: the manifest, the README, license files, and configuration. This separation keeps non-code files out of the source tree.
For a binary project, cargo new writes src/main.rs:
fn main() {
println!("Hello, world!");
}The file is the crate root of the binary crate. A crate is the unit that rustc compiles. The crate root is the file where compilation starts, and the function main in it is the program's entry point.
Cargo finds src/main.rs by convention, and you don't list it in Cargo.toml. The conventions go further than this one file:
src/main.rsis the root of a binary crate with the same name as the package.src/lib.rsis the root of a library crate with the same name as the package.- Files in
src/bin/each become a separate binary. - Files in
tests/become integration tests. - Files in
examples/become example programs. - Files in
benches/become benchmarks.
A package can have both src/main.rs and src/lib.rs. It then contains two crates, a library and a binary, and both take the package name. Many projects use this layout to keep logic in the library and leave main.rs as a thin wrapper.
The manifest
Cargo.toml is the manifest. It is written in TOML, a configuration format made of tables (headers in square brackets) and key-value pairs. A fresh manifest looks like this:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]The edition value depends on your Cargo version. Newer toolchains write a newer edition. An edition is an opt-in set of language changes that lets Rust evolve without breaking old code. Crates built with different editions can be linked together in the same program.
The [package] table describes the package:
nameis the package name, and it is the default name of the compiled binary.versionfollows semantic versioning, in the formmajor.minor.patch.editionselects the language edition used to compile the crate.
[dependencies] starts empty. Chapters later in this tutorial add entries to it.
The package name has rules. Cargo rejects names that are not valid in crate form, and it warns about names that collide with Rust keywords or standard library crates. A package named hello-cargo (with a hyphen) is allowed, but the crate name used inside Rust code replaces the hyphen with an underscore. The binary file keeps the hyphen: it is target/debug/hello-cargo.
The lock file
After your first cargo build, cargo run, or cargo check, a new file appears: Cargo.lock. For a project with no dependencies it is short:
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "hello_cargo"
version = "0.1.0"The version line at the top is the lock file format version. It depends on your Cargo version, so you may see a different number.
Cargo.toml states what you want, such as "any rand compatible with 0.8". Cargo.lock records what Cargo actually resolved: the exact version of every package in the dependency tree, including indirect ones. With the lock file in place, a build on another machine or next month uses the same versions. Without it, Cargo would pick the newest compatible versions each time, and a new release could change your build.
Treat the lock file as generated output:
- Do not edit it by hand.
- Commit it for applications, so that builds are reproducible.
- For libraries, the common older advice was to leave it out of version control, because downstream users resolve their own versions. Current Cargo guidance says either choice is acceptable, and many teams commit it anyway so that CI runs are stable.
To refresh the locked versions, run cargo update. It rewrites Cargo.lock with the newest versions that still satisfy the constraints in Cargo.toml.
The target directory
Building creates a target directory next to Cargo.toml. It holds everything the compiler produces. After cargo build, the layout looks like this:
target/
├── CACHEDIR.TAG
└── debug/
├── build/
├── deps/
├── examples/
├── incremental/
├── hello_cargo
└── hello_cargo.dThe pieces you will meet most often:
target/debug/holds output from the default development profile.cargo build --releasewrites totarget/release/instead.target/debug/hello_cargois the executable. On Windows it ishello_cargo.exe.deps/holds compiled dependencies and intermediate files.incremental/holds data that speeds up repeated builds..dfiles record which source files the output depends on.CACHEDIR.TAGtells backup tools that the directory is a cache and can be skipped.
cargo check also writes to target/debug, but it produces only metadata, not a runnable binary. That is why it is faster than a full build.
Because target is regenerable, you can delete it at any time with cargo clean. The next build recreates it. The directory can grow to several gigabytes in projects with many dependencies, so cargo clean is also the quick fix when you need disk space.
The generated `.gitignore`
For a new project, Cargo writes a .gitignore containing one line:
/targetThis keeps compiled output out of version control. Note that the generated file does not list Cargo.lock. Cargo's default for a binary project is to commit it. For a library created with cargo new --lib, the generated .gitignore in older Cargo versions also listed Cargo.lock. Newer versions no longer do so.
If the project is inside an existing Git repository, Cargo does not create a new repository. You can control this with a flag:
cargo new hello_cargo --vcs noneThe --vcs option accepts git, hg, pijul, fossil, or none. With none, Cargo creates no repository and no .gitignore. The target directory is then yours to ignore.
A diagram of the whole flow
The diagram shows which command produces which file.
Library projects look different
Pass --lib to create a library crate:
cargo new my_library --libThe only difference in layout is the root file. Instead of src/main.rs, you get src/lib.rs. In recent Cargo versions it contains a sample function and a test:
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}The exact sample depends on the Cargo version. Older versions used usize and a different test body. A library has no main function, so cargo run fails on it with an error that no binary target is available. Use cargo test or cargo build instead.
Creating a project in an existing directory
cargo new makes a new directory and fails if one with that name exists. If you already have a directory, use cargo init inside it:
mkdir existing_dir
cd existing_dir
cargo initcargo init writes the same files, and it takes the package name from the directory name. It does not overwrite files that are already there. If a src/main.rs exists, Cargo leaves it alone.
Common problems
Cargo.lockis missing. It is created on the first build, check, or test. You have not done anything wrong.- Changing
Cargo.tomltriggers a rebuild. Cargo compares the manifest to what it built before, and any change to the package or its dependencies causes recompilation. - A
srcfile is ignored. Cargo compiles only files reachable from the crate root. A new file such assrc/helpers.rsis not part of the build untilmain.rsorlib.rsdeclares it withmod helpers;. - The binary has a different name than expected. The binary name comes from
namein[package], not from the directory name. Renaming the directory does not rename the package. error: package ... cannot be built because it requires rustc .... The manifest can name a minimum Rust version in arust-versionkey. Runrustup updateif your toolchain is older.
The mod rule catches many newcomers, so here is a complete example. Create src/helpers.rs:
pub fn greeting() -> &'static str {
"Hello from helpers"
}Then declare the module in src/main.rs:
mod helpers;
fn main() {
println!("{}", helpers::greeting());
}Without the mod helpers; line, the compiler never reads helpers.rs, and the call fails with an unresolved-name error.
Exercises
Exercise
You run cargo new demo and then list the project files before building anything. Which files are present, and which file appears only after the first build?
Show answer
Before building, the project has Cargo.toml, src/main.rs, and .gitignore (plus a .git directory if Cargo initialized a repository). Cargo.lock and the target directory appear after the first cargo build, cargo run, or cargo check.
Exercise
You add src/utils.rs to a binary project and call utils::run() from main. The compiler reports an unresolved name. What is missing, and where does it go?
Show answer
The module declaration mod utils; is missing. It goes in src/main.rs, the crate root, above the code that uses utils::run(). Cargo compiles only files that the crate root declares as modules, so the file is ignored until then. The function must also be marked pub to be called from main.
Exercise
Your target directory has grown to several gigabytes. Is it safe to delete it, and what is the command that does so?
Show answer
Yes, it is safe. The directory holds only generated output. Run cargo clean to remove it. The next cargo build recreates it, though that build takes longer because everything must be recompiled.