Sub topic 2
Creating Your First Project with `cargo new`
This chapter assumes you can use a terminal and understand that a compiler turns source code into an executable program. Cargo is Rust’s build tool and package manager.
Creating a Project
Run:
cargo new hello_cargo
cd hello_cargo
cargo runcargo new creates a new binary project. A binary project produces a program you can run. Cargo creates the project directory, initializes version control metadata when appropriate, and writes starter files.
The command output should include Hello, world!. Cargo first compiles the project, then runs the compiled program.
What Cargo Generates
A new project has this basic structure:
hello_cargo/
├── Cargo.toml
├── src/
│ └── main.rs
└── .gitignoreCargo.toml is the manifest. It describes the package name, version, Rust edition, and dependencies. A dependency is an external library that your project uses.
src/main.rs contains the program’s entry point:
fn main() {
println!("Hello, world!");
}target/ appears after Cargo builds the project. It contains build artifacts, including compiled files. You normally do not edit this directory or commit it to version control.
Building, Running, and Checking
Use these commands from the project directory:
cargo check
cargo build
cargo run
cargo build --releasecargo check finds compilation and type errors without producing a final executable. It is usually the fastest feedback loop.
cargo build creates a debug build under target/debug. Debug builds compile quickly and retain information useful during development. cargo build --release creates an optimized build under target/release, which is intended for distribution or performance testing.
A common error is running a Cargo command outside a project directory. Cargo searches the current directory and its parents for Cargo.toml. Change into hello_cargo before running the commands.
Exercise
Which command checks whether a project compiles without creating a final executable?
Show answer
cargo check.