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
- The main function is the entry point of every Rust program.
- It marks the start of the program's execution.
- 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.
- Each statement in Rust ends with a semicolon, indicating the end of the statement.
1. fn main():
2. println! Macro:
3. Semicolon (;):
Running the Program
- Download and install Rust from the official website
- Use the Cargo build system to set up your project:
1. Install Rust:
2. Create a New 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
- Rust uses macros like println! for tasks such as formatted output. They differ from functions but behave similarly.
- The syntax is clean and emphasizes safety, which is a core philosophy of Rust.
- The simplicity of this example makes Rust approachable for new programmers.
1. Macros in Rust:
2. Safe and Concise:
3. Beginner-Friendly:
Rust Language Questions, Answers, and Code Snippets Collection.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics