Introduction to Rust: Writing Your First "Hello, World!"

Getting Started with Rust: A Beginner’s Guide

Getting Started with Rust: A Beginner’s Guide

Setting Up the Workspace

First, we need to establish a directory to store our code. While Rust is indifferent to its location, it is good practice to keep your projects well-organized.

Open a terminal (or command prompt) and create a directory for your project.

For Linux, macOS, and PowerShell (on Windows):

# Create a "projects" directory in your home directory
mkdir ~/projects

# Enter the newly created directory
cd ~/projects

# Create the directory for our specific project
mkdir hello_world

# Enter the project directory
cd hello_world

For the Windows Command Prompt (CMD):

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir hello_world
> cd hello_world

Writing and Executing the Program

Now that we are in the correct directory, let's create a source file named main.rs. Rust source files always use the .rs extension. If a filename consists of multiple words, the convention is to use an underscore, such as hello_world.rs.

Open the main.rs file in a text editor and insert the following code:

File: main.rs

fn main() {
    println!("Hello, world!");
}

Save the file and return to your terminal. To compile and execute the program, use the following commands:

On Linux or macOS:

$ rustc main.rs
$ ./main

On Windows:

> rustc main.rs
> .\main.exe

Regardless of your operating system, you should see the following output in your terminal:

Hello, world!

Congratulations! You have successfully written and executed your first Rust program. Welcome to the community! 🎉

Anatomy of Our Program

Let's analyze the code we've written, component by component:

fn main() {
    println!("Hello, world!");
}

fn main(): This defines a function named main. This is the entry point for every executable Rust program.

{}: The curly braces define the function body.

Within the main function, we have a single line:

println!("Hello, world!");

println!: This is a Rust macro (indicated by the exclamation mark !) used to print output to the terminal.

"Hello, world!": A string literal passed as an argument.

;: A semicolon ends the statement, as is common in Rust.

Two Distinct Steps: Compilation and Execution

Unlike interpreted languages like Python or JavaScript, Rust is an ahead-of-time (AOT) compiled language. This means the program goes through two separate phases:

  1. Compilation: The command rustc main.rs invokes the Rust compiler to convert the source code into a binary executable.
  2. Execution: Run the compiled binary with ./main (or .\main.exe on Windows).

This approach enables you to distribute the executable without requiring users to install Rust.

Comments

Popular posts from this blog

Euler's Totient Theorem: The Secret World of Modular Exponents

Esponenziazione Modulare: Come Gestire Numeri Giganti in Crittografia