Rust for Python Programmers #2 — Hello World!
Welcome back, fellow Pythonistas turned Rust enthusiasts! Now that you’ve got Rust installed, it’s time to dive into your first Rust program. In this post, we’ll walk through creating the classic “Hello, World!” program in both Rust and Python, highlighting the syntax differences along the way.
The Traditional “Hello, World!” Program
Python Version
Let’s start with the familiar territory of Python:
print("Hello World!")
Python’s simplicity shines through in this concise one-liner. The print()
function takes care of displaying our message on the screen.
Rust Version
Now, let’s replicate the same result in Rust:
fn main() {
println!("Hello, World!");
}
Here’s where things start to look a bit different. In Rust, the fn main()
syntax defines the entry point of the program. Similarly to Python's print()
, Rust uses the println!()
macro to achieve output.
Breaking Down the Rust Version
fn main()
: This is the declaration of themain
function, which serves as the entry point of a Rust program. Rust requires amain
function to begin execution.println!()
: In Rust, macros are invoked using the!
symbol. Macros are similar to functions but operate at the syntactic level, allowing for more flexible code generation.println!
prints its arguments to the console."Hello, World!"
: Just like in Python, we provide the text we want to print as an argument toprintln!()
.
Compilation and Execution
Unlike Python, Rust is a compiled language. This means that before running a Rust program, you need to compile it into an executable binary. Let’s do this:
- Save the Rust code: Create a file named
main.rs
and paste the Rust code inside. - Compile the code: Open a terminal, navigate to the directory containing
main.rs
, and run the following command:rustc main.rs
- Run the program: Execute the compiled binary by running:
./main
- Voilà! You’ll see the “Hello, World!” message displayed on your terminal.
Comparing Python and Rust
While the syntax for “Hello, World!” in Rust might seem a bit more verbose compared to Python, it may be related to Rust’s emphasis on safety and performance. This comes at the cost of some initial complexity. Anyway, so far we haven’t seen much difference, right?