w3resource

Your first Rust Program: Hello World


Writing Your First Rust Program: Hello World

The "Hello, World!" program is a simple way to get started with any programming language. In Rust, it introduces basic syntax, the concept of functions, and printing to the console. This guide walks through the process of writing, running, and understanding the "Hello, World!" program in Rust.


Syntax

Here is the code for the "Hello, World!" program in Rust:

fn main() {
    // Print "Hello, World!" to the console
    println!("Hello, World!");
}

Explanation

    1. fn main():

    • The main function is the entry point of every Rust program.
    • It marks the start of the program's execution.

    2. println! Macro:

    • println! is a macro that prints text to the console, followed by a newline.
    • The text is enclosed in double quotes and passed as an argument to the macro.

    3. Semicolon (;):

    • Each statement in Rust ends with a semicolon, indicating the end of the statement.

Running the Program

    1. Install Rust:

    2. Create a New Project:

    • Use the Cargo build system to set up your project:
    • Code:

      cargo new hello_world
      cd hello_world
      

    3. Edit the Code:

    • Open the src/main.rs file in a text editor and replace its contents with the "Hello, World!" program.

    4. Build and Run:

    • Build and execute your program with:
    • Code:

      cargo run
      

Output:

Hello, World!

Expanding the "Hello, World!" Program

Printing Multiple Lines

You can print multiple messages:

Code:

fn main() {
    // Print the first message
    println!("Hello, World!");
    
    // Print another message
    println!("Welcome to Rust programming!");
}

Output:

Hello, World!
Welcome to Rust programming!

Using Variables

You can include variables in your output:.

Code:

fn main() {
    let name = "Miron"; // Declare a variable
    println!("Hello, {}!", name); // Use the variable in the output
}

Output:

Hello, Miron!

Key Takeaways

    1. Macros in Rust:

    • Rust uses macros like println! for tasks such as formatted output. They differ from functions but behave similarly.

    2. Safe and Concise:

    • The syntax is clean and emphasizes safety, which is a core philosophy of Rust.

    3. Beginner-Friendly:

    • The simplicity of this example makes Rust approachable for new programmers.

Rust Language Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.