So, You Wrote Some Rust Code... Now What?
Alright, you’ve written your first Rust program—congratulations! But how do you actually run it? Don't worry, my fellow Rustacean, because I’ve got you covered. Let’s walk through the different ways to execute your shiny new Rust code.
1. Running a Rust Program the Quick Way
If you just want to test your code without compiling it into an executable, you can use cargo run
(if you're using Cargo, which you should be!).
cargo run
This command will:
- Compile your code
- Run the executable
- Show the output
Boom! You just ran your first Rust program the easy way.
2. Compiling and Running Manually
If you prefer the old-school way (or just love typing commands), you can compile Rust code using rustc
:
rustc main.rs
./main # Run the compiled program (Linux/macOS)
main.exe # Run the compiled program (Windows)
This will create an executable file (main
on Linux/macOS or main.exe
on Windows), which you can run anytime.
3. Running Rust Code Without Installing Anything
Feeling lazy? (I get it, no judgment.) You can run Rust code directly in your browser using Rust Playground. Just paste your code, hit Run, and watch the magic happen!
4. Debug vs. Release Mode
Rust has two modes:
- Debug mode (default): Slower but includes extra debugging information.
- Release mode: Optimized for speed and efficiency.
To compile in release mode, use:
cargo build --release
Then run:
./target/release/main
Your Rust program will now run at warp speed!
5. Handling Command-Line Arguments
Want to make your program more interactive? You can pass arguments:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("You passed: {:?}", args);
}
Run it like this:
cargo run -- arg1 arg2
And Rust will output:
You passed: ["target/debug/main", "arg1", "arg2"]
Now you know how to run Rust programs like a pro! Whether you’re using cargo run
, compiling manually, or testing in the browser, you’ve got all the tools to make your Rust code come to life. Happy coding!
0 Comments