Lesson 2: Hello, Rust! Your First Program
Writing Your First Rust Program
Let’s jump right in:
1. Open your terminal or use the Rust Playground.
2. Enter this code:
fn main() {
println!("Hello, Rustaceans!");
}
Code Breakdown
fn main() { ... }
: Every Rust program starts by running themain
function.println!("Hello, Rustaceans!");
: This prints a message to the screen.- The
!
means you’re calling a macro (a special kind of function). - The text inside the quotes is your message.
- The
Interactive Task 1: Run Your Code
- Run the code above.
- You should see this output:
Hello, Rustaceans!
Making It Your Own
Try changing the text inside the quotes to print your name or any other message:
fn main() {
println!("Welcome to the world of Rust!");
}
Challenge: Print Two Lines Instead of One
Try this:
fn main() {
println!("Rust makes programming fun!");
println!("Let's keep learning together!");
}
How Rust Runs Your Program
- Compile: Turning your code into machine instructions — use
rustc your_file.rs
if using your terminal. - Run: Execute the compiled program to see the output.
(If using the Rust Playground, just hit “Run”.)
Mini-Challenge
Write a Rust program that prints:
Learning Rust is rewarding!
Keep going!
Hint: Use two println!()
statements. You can add a blank line between them by using println!("");
.
Solution: https://gist.github.com/rust-play/4c81ad149c9273edeaed5d41ffbebb54
Recap
- You wrote and ran your first Rust program.
- You now understand the
main
function and how Rust prints output. - You modified the program and tried a mini-challenge!
Go to Course Structure or Navigate to next blog!