Basics
Rust Running Code
Running Rust Programs
Rust programs run via cargo run or rustc with .rs files.
Introduction to Running Rust Code
Running Rust code is an essential skill for developers working with this powerful systems programming language. In this post, we'll explore the two main methods to run Rust programs: using the cargo run
command and the rustc
compiler with .rs
files.
Using Cargo to Run Rust Code
Cargo is Rust's package manager and build system. It simplifies managing dependencies, building, and running your Rust applications. To run a Rust program with Cargo, navigate to your project's directory and execute the following command:
The cargo run
command compiles your code and runs the resulting executable. This is the preferred method for running Rust programs during development because it automatically handles dependencies and ensures your project is up to date.
Using Rustc to Compile and Run
The rustc compiler is another way to run Rust code, offering more control over the compilation process. This method is useful for small scripts or when you need to compile a single .rs
file. To compile and run a Rust file using rustc
, use the following steps:
First, this command compiles the main.rs
file into an executable. Then, the ./main
command executes the compiled program. This process requires manual management of dependencies and is not as convenient for larger projects as using Cargo.
Conclusion
Both cargo run
and rustc
are valuable tools for running Rust code. For most development workflows, cargo run
is more convenient due to its integration with the Cargo ecosystem, which manages dependencies and builds. However, rustc
can be useful in simpler scenarios or when you need finer control over the compilation process.
Basics
- Previous
- Installation
- Next
- Syntax