Project Structure
What is Cargo?
Cargo is Rust's build system and package manager which streamlines almost every aspect of your Rust workflow:
- Project Creation:
cargo newquickly sets up a new Rust project with the correct structure. - Building:
cargo buildcompiles your code into an executable program. - Running:
cargo runbuilds and then executes your program. - Testing:
cargo testruns your project's tests.
Let's create our classic "Hello, world!" program using Cargo.
- Create a New Project:
- In your terminal, navigate to a directory where you want to create your project (e.g., your Desktop or a
devfolder). - Run this command:
cargo new hello_rust_app - Cargo will create a new folder named
hello_rust_appwith a basic project structure inside.
- In your terminal, navigate to a directory where you want to create your project (e.g., your Desktop or a
- Explore the Project Structure:
- Navigate into the new folder:
cd hello_rust_app - Look at the contents:
Cargo.toml: This is the manifest file for your project. It contains metadata about your project (name, version) and lists its dependencies.src/main.rs: This is where your main Rust code lives.target/: (Created after you build) This is where compiled executable files go.
- Navigate into the new folder:
- Examine
src/main.rs:- Open
src/main.rsin your VS Code. You'll see:fn main() {
println!("Hello, world!");
}fn main(): This is the main function, the entry point of every Rust executable program.println!: This is a macro (indicated by the!). It prints text to the console.
- Open
- Run Your Application:
- In your terminal (make sure you're inside the
hello_rust_appfolder), run:cargo run - What happens?
- Cargo first compiles your code (you'll see messages like "Compiling hello_rust_app v0.1.0...").
- Then, it executes the compiled program.
- You should see:
Hello, world!printed in your terminal.
- In your terminal (make sure you're inside the
Congratulations! You've just created and run your very first Rust application.