Rust Programming Language: Basic Project Workflow with Cargo
Rust is a systems programming language focused on safety, performance, and concurrency. It achieves memory safety without using a garbage collector, and its powerful type system and ownership model guarantee memory safety and thread safety.
Cargo is Rust’s build system and package manager. It handles tasks like:
- Creating new Rust projects.
- Building your code.
- Downloading and compiling your code’s dependencies.
- Running tests.
- Generating documentation.
1. Creating a New Rust Project (cargo new)
The cargo new command is used to create a new Rust project (either an executable application or a library) with a standardized directory structure.
cargo new <project-name>
# Example:
cargo new my-rust-app<project-name>: The name of your new project. Cargo will create a directory with this name.
By default, cargo new creates a binary project (an executable application).
- To create a binary project:
cargo new <project-name>(default) orcargo new <project-name> --bin. - To create a library project:
cargo new <project-name> --lib.
2. Basic Cargo Commands
Once you’ve created a project, navigate into its directory (cd my-rust-app).
Build the Project (cargo build)
This command compiles your project’s source code and its dependencies into an executable binary (for binary projects) or a library (for library projects). The compiled output is placed in the target/debug/ directory.
cargo buildRun the Project (cargo run)
This command compiles your project (if necessary) and then runs the resulting executable. It’s a convenient way to execute your application during development.
cargo runCheck the Project (cargo check)
cargo check performs a fast compilation check without actually producing an executable. It’s useful for quickly catching errors as you code, without waiting for a full build.
cargo checkRun Tests (cargo test)
This command compiles and runs all tests defined in your project.
cargo test3. Automatic Re-execution on File Changes (cargo watch)
cargo watch is a third-party utility that automatically re-executes specified Cargo commands whenever your source code files change. This is incredibly useful for rapid development feedback.
Installation
cargo install cargo-watchUsage: Automatically Rerun Tests
cargo watch -x test-x test: Executescargo testwhenever a relevant file changes. You can replacetestwith any other Cargo subcommand (e.g.,run,build,check).
Usage: Automatically Rerun the Application
cargo watch -x runThis command is perfect for web development or services that need to restart upon code changes.