#2 Hello, World!
cargo new, cargo run
Create a project
Cargo makes it easy to create a new Rust project. The cargo new command generates everything you need to get started:
$ cargo new hello-project
Created binary (application) `hello-project` packageThis creates a new directory called hello-project with a complete project structure, including a Git repository.
Project structure
Let's look at what Cargo generated:
hello-project/
├── Cargo.toml # Project metadata and dependencies
└── src/
└── main.rs # Your Rust source codeCargo.toml is the manifest file. It contains your project's name, version, and dependencies:
[package]
name = "hello-project"
version = "0.1.0"
edition = "2021"
[dependencies]The main function
Every Rust program starts with a main function. Cargo generated a simple one for you in src/main.rs:
fn main() {
println!("Hello, world!");
}Let's break this down:
fn declares a function. main is the entry point of every Rust program. println! is a macro (notice the !) that prints text to the console with a newline at the end.
Build and run
To compile and run your project in one step, use cargo run:
$ cargo run
Compiling hello-project v0.1.0 (/home/user/hello-project)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/hello-project`
Hello, world!If you only want to compile without running, use cargo build. The compiled binary will be at target/debug/hello-project.
To quickly check your code compiles without producing a binary, use cargo check — it's faster than a full build.
Your turn
Try creating a project and running it. Use cargo new, cargo run, and cargo build in the terminal below: