rustc and cargo šÆWelcome to our comprehensive guide on Rust, a powerful and modern system programming language. In this tutorial, we'll delve into two essential tools in the Rust ecosystem: rustc and cargo. By the end of this lesson, you'll have a solid understanding of these tools and how they work together to help you build Rust projects. š
rustc? š”rustc is the Rust compiler. It's responsible for translating your Rust source code (.rs files) into machine-readable code. Think of it as the bridge between your code and the computer that runs it.
Let's start with a simple main.rs file:
fn main() {
println!("Hello, World!");
}To compile this file using rustc, open a terminal and navigate to the directory containing main.rs. Then, run the following command:
rustc main.rs -o mainThis command compiles main.rs and generates an executable named main. You can run it with:
./mainš” Pro Tip: You can skip the -o main part to create an executable with the same name as your source file, like so: rustc main.rs
Now, let's add a variable and a function to our main.rs:
fn main() {
let message = "Hello, World!";
print_message(message);
}
fn print_message(message: &str) {
println!("{}", message);
}To compile and run this code, use the following commands:
rustc main.rs -o main
./maincargo? š”cargo is the Rust package manager and build tool. It simplifies the process of managing dependencies, building, and running Rust projects.
Create a new project by running the following command:
cargo new my_projectThis command creates a new Rust project named my_project with a Cargo.toml configuration file and a src directory containing a main.rs file.
To build and run the project, navigate to the project directory and use the following command:
cargo runThis command builds the project and runs the generated executable.
cargo makes managing dependencies easy. To add a dependency, edit the Cargo.toml file:
[dependencies]
reqwest = "0.11.9"To update dependencies, use the following command:
cargo updaterustc and cargo š”While both tools are essential for Rust development, they serve different purposes. rustc compiles Rust source code into executables, while cargo manages dependencies and simplifies the build process.
Question: What command compiles a Rust project built with cargo?
A: rustc
B: cargo build
C: cargo compile
Correct: B
Explanation: cargo build is the command used to compile a Rust project built with cargo.