To run a Rust file, you typically follow a two-step process: compile the source code into an executable program and then execute that program.
Here's a straightforward guide based on the provided reference:
Understanding the Process
Rust is a compiled language. This means that before you can run your code, you must use the Rust compiler (rustc
) to translate your human-readable source file (usually ending in .rs
) into a machine-readable executable file. Once compiled, you can then run the generated executable.
Compiling and Running Your Rust Code
The specific commands to compile and run a Rust file depend slightly on your operating system.
Step 1: Compile the File
Navigate to the directory where your .rs
file is saved using your terminal or command prompt. Use the rustc
command followed by the name of your file. For example, if your file is named main.rs
:
rustc main.rs
This command reads your main.rs
file and creates an executable file in the same directory. The executable will be named main
on Linux/macOS and main.exe
on Windows.
Step 2: Run the Executable
After successful compilation, you can run the generated executable.
-
On Linux or macOS:
Use the./
prefix followed by the executable name../main
-
On Windows:
Use the.\
prefix followed by the executable name (which includes the.exe
extension)..\main.exe
If your code prints output, you will see it in the terminal. For instance, a simple "Hello, world!" program would display:
Hello, world!
Command Summary
Here's a quick summary of the commands:
Operating System | Compile Command | Run Command | Example Output |
---|---|---|---|
Linux / macOS | rustc main.rs |
./main |
Hello, world! |
Windows | rustc main.rs |
.\main.exe |
Hello, world! |
Note: The reference specifically mentions these commands: $ rustc main.rs $ ./main Hello, world!
for Linux/macOS and rustc main.rs .\\main.exe Hello, world!
for Windows, illustrating both the command and the expected output.
Using cargo run
(Alternative)
For more complex projects or when using Rust's build tool and package manager, Cargo, you can use the cargo run
command. This command automatically handles both compiling your project and running the resulting executable. It's the preferred method for most Rust development workflows.
To use cargo run
, make sure you are in the root directory of your Cargo project (the directory containing the Cargo.toml
file).
cargo run
This is often simpler as you don't need to manually manage the compiler (rustc
) or the resulting executable file paths.
In summary, you compile your .rs
file with rustc
and then execute the resulting file, or you can use cargo run
for projects managed by Cargo.