Here’s how to create a simple “Hello, World!” project step by step
Step 1: Install Rust and Cargo
First, ensure Rust and Cargo are installed on your system. Rustup, the Rust toolchain installer, installs both Rust and Cargo.
- Open a terminal.
- Run the following command to install Rust and Cargo
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- Follow the on-screen instructions to complete the installation.
- Restart your terminal, or run
source $HOME/.cargo/envto configure your current shell.
Step 2: Create a New Cargo Project
- Navigate to the directory where you want to create your project.
- Run the following command:
cargo new hello_world
- This command creates a new directory named
hello_worldwith the following structure:
hello_world/
├── Cargo.toml
└── src/
└── main.rs
Cargo.tomlis the manifest file for Rust projects, containing metadata and dependencies.src/main.rsis the main source file where your Rust code will reside.
Step 3: Understand the Generated Code
Open src/main.rs in your favorite text editor. You’ll see the following Rust code:
fn main() {
println!("Hello, world!");
}
fn main()declares the main function, the entry point of the program.println!("Hello, world!");is a macro that prints the string “Hello, world!” to the console.
Step 4: Build and Run the Project
- Return to your terminal and navigate to your project directory (
hello_world). - Run the project with Cargo by executing:
cargo run
- Cargo compiles the project and then runs the resulting executable. You should see the output:
Hello, world!
- The first time you run
cargo run, Cargo will compile your project and then execute it. Subsequent runs will be faster as Cargo only recompiles if changes are detected.
Step 5: Minimal Use of Cargo Packages
The newly created project doesn’t include any external packages by default. The Cargo.toml file only lists the project itself and does not include dependencies on external crates. Here’s what Cargo.toml might look like:
[package]
name = "hello_world"
version = "0.1.0"
edition = "2018"
[dependencies]
- The
[package]section defines metadata about your project. - The
[dependencies]section is where you would add external package dependencies, which is empty for this project.
Conclusion
You’ve now created a simple Rust project using Cargo, wrote a “Hello, World!” program, and ran it. This project is a fundamental stepping stone in Rust development, demonstrating Rust’s ease of setup and the powerful tooling provided by Cargo.
💬 Comments
Comments are not enabled for this article yet.