.rs FileTo compile an existing Rust source file (.rs), you can create a new Cargo project around it or use the Rust compiler directly. Here’s how to do both.
.rs File With CargoAssuming you have an existing Rust file called greeting.rs that looks like this:
// greeting.rs
fn main() {
println!("Hello from an existing Rust file!");
}
If you haven't already, create a new Cargo project:
cargo new my_project
cd my_project
Move your existing .rs file into the src directory:
mv path/to/greeting.rs src/
Cargo.tomlOpen Cargo.toml and set the name to match your project, if necessary.
main.rsReplace the contents of main.rs with the following code to include greeting.rs:
// src/main.rs
mod greeting;
fn main() {
greeting::main();
}
Compile the project with:
cargo build
After building, you can run your program:
./target/debug/my_project
This should display:
Hello from an existing Rust file!
rustcIf you prefer not to use Cargo and just want to compile the existing .rs file directly, you can employ the Rust compiler (rustc).
Navigate to the directory where greeting.rs is located.
Run the following command:
rustc greeting.rs
This compiles greeting.rs and creates an executable called greeting (or greeting.exe on Windows).
./greeting # Linux or macOS
.\greeting.exe # Windows
You should see:
Hello from an existing Rust file!
| Command | Description |
|---|---|
cargo new my_project |
Creates a new Rust project |
mv path/to/greeting.rs src/ |
Moves an existing .rs file to the project |
cargo build |
Compiles the project |
./target/debug/my_project |
Runs the debug binary |
rustc greeting.rs |
Compiles greeting.rs without Cargo |
./greeting |
Runs the compiled binary |
This guide demonstrates how to work with an existing Rust file, using either Cargo or the Rust compiler directly.