If you’re coming from Python, you’re probably used to running .py
files directly with the Python interpreter. In Rust, the process involves compiling your code first before running it. Let’s walk through how to create a simple Rust file and run it.
Before we begin, you’ll need to install Rust if you haven’t already. You can do this using the following command:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
This will install rustup
, Rust’s toolchain manager. After installation, make sure rustc
(the Rust compiler) and cargo
(Rust’s build system) are properly installed by running:
rustc --version
cargo --version
In Rust, the source files usually end with the .rs
extension. Let’s create a new file called main.rs
:
touch main.rs
Now open the file in your favorite editor and add the following code:
fn main() {
println!("Hello, Rust!");
}
This is a simple Rust program that prints "Hello, Rust!"
to the console. It’s equivalent to the classic “Hello, World!” example.
Unlike Python, which runs scripts directly, Rust code must be compiled before execution. To compile the program, run the following command:
rustc main.rs
This will create an executable file (for example, main
on Unix-based systems or main.exe
on Windows). To run the program, execute the following:
./main # On Unix-based systems (Linux/macOS)
main.exe # On Windows
You should see the output:
Hello, Rust!
cargo
for Larger ProjectsFor more complex projects, Rust developers typically use cargo
, Rust’s package manager and build system. It simplifies compiling and running Rust projects. To create a new project with cargo
, use:
cargo new my_project
cd my_project
cargo run
This sets up a basic project structure and runs the program for you, making it easier to manage larger Rust codebases.
Now that you know how to create and run a simple Rust program, you’re ready to start experimenting with Rust code. In the next sections, we’ll dive deeper into Rust’s unique features, starting with Basic Syntax and Structuring.
If you're eager to continue this learning journey and stay updated with the latest insights, consider subscribing. By joining our mailing list, you'll receive notifications about new articles, tips, and resources to help you seamlessly pick up Rust by leveraging your Python skills.
000 - Learning Rust as a Pythonista: A Suggested Path
002 - Learning Rust as a Pythonista: Basic Syntax and Structure
006 - Rust Traits vs. Python Duck Typing: A Comparison for Pythonistas
007 - Concurrency in Rust for Python Developers