Hello, world and Cargo
Compiling a single file with rustc, then letting Cargo manage the project, the build and the binary.
- Compile and run a single Rust file with rustc
- Create, build and run a project with Cargo
- Know what Cargo.toml, Cargo.lock and target/ are for
The smallest Rust program is the same in both folders:
fn main() {
println!("Hello, world!");
}
Execution starts at fn main. println! ends in ! because it is a macro, not a function: it checks the format string against its arguments at compile time, so a missing argument is a compile error rather than garbage at run time.
Two ways to build it
basics/hello_world/ uses the compiler directly:
rustc hello.rs
./hello
That is fine for one file. Real projects use Cargo, Rust’s build system and package manager, which is what every other folder in basics/ is:
cargo new hello_cargo # Cargo.toml, src/main.rs, and a git repository
cd hello_cargo
cargo build # compiles to target/debug/hello_cargo
cargo run # builds if anything changed, then runs
cargo build --release # optimised build in target/release/
Cargo.toml describes the package — name, version, and the edition, here 2021, which pins the language rules the crate is compiled with. Dependencies go under [dependencies]; Cargo downloads and builds them, and records the exact versions it chose in Cargo.lock, so every later build uses the same ones.
One housekeeping note: basics/hello_world/ also contains hello, the compiled binary. Build outputs are usually left out of version control — Cargo’s own .gitignore excludes target/ for exactly this reason — so the binary can be deleted and rebuilt at any time.
Try it yourself. In hello_cargo, run cargo build twice and compare the timings, then cargo build --release and compare the binary sizes in target/debug/ and target/release/. Add rand = "0.8" under [dependencies] and watch what cargo build does — and what appears in Cargo.lock.