0
0
Rustprogramming~15 mins

Writing first Rust program - Deep Dive

Choose your learning style9 modes available
Overview - Writing first Rust program
What is it?
Writing your first Rust program means creating a simple piece of code that runs in the Rust language. Rust is a programming language that helps you build fast and safe software. The first program usually prints a message on the screen to show that everything is working. This step introduces you to Rust's basic structure and how to run code.
Why it matters
This exists to help you start coding in Rust, which is known for preventing many common bugs and crashes. Without this step, you wouldn't know how to write or run Rust code, making it impossible to build software with it. Starting with a simple program builds confidence and shows how Rust works in practice.
Where it fits
Before this, you should know what programming is and have a basic idea of how computers run instructions. After this, you will learn about variables, data types, and control flow in Rust to write more complex programs.
Mental Model
Core Idea
A Rust program is a set of instructions that the computer follows, starting from a main function that runs the code step by step.
Think of it like...
Writing your first Rust program is like learning to say 'Hello' in a new language; it’s a simple start that shows you can communicate and sets the stage for more complex conversations.
┌─────────────────────────────┐
│        Rust Program         │
├─────────────────────────────┤
│ fn main() {                │
│     println!("Hello, world!"); │
│ }                          │
└─────────────────────────────┘

Start here → run code → see output
Build-Up - 6 Steps
1
FoundationUnderstanding Rust program structure
🤔
Concept: Learn the basic parts of a Rust program, especially the main function where execution starts.
In Rust, every program starts with a special function called main. This is where the computer begins running your instructions. The main function looks like this: fn main() { // your code here } Inside the curly braces { }, you write the commands you want the computer to do.
Result
You know where to put your code so the computer can run it.
Understanding that main is the entry point helps you organize your Rust code correctly from the start.
2
FoundationPrinting text to the screen
🤔
Concept: Learn how to show messages on the screen using Rust's println! macro.
Rust uses a special command called println! to print text. The exclamation mark means it's a macro, a tool that helps write output. For example: println!("Hello, world!"); This line tells the computer to show the words Hello, world! on the screen.
Result
You can display messages to the user or yourself for checking what the program does.
Knowing how to print output is the first step to interacting with your program and debugging it.
3
IntermediateRunning your Rust program
🤔Before reading on: Do you think you need to compile Rust code before running it, or can you run it directly like a script? Commit to your answer.
Concept: Learn how to compile and run Rust code using the Rust compiler and Cargo tool.
Rust code must be compiled into a program the computer can run. You use the command line to do this: 1. Save your code in a file named main.rs. 2. Open a terminal and type: rustc main.rs 3. This creates an executable file. 4. Run it by typing ./main on Linux/Mac or main.exe on Windows. Alternatively, use Cargo, Rust's build tool: cargo new hello cd hello cargo run Cargo compiles and runs your program in one step.
Result
Your program runs and shows the output on the screen.
Understanding compilation and running helps you move from writing code to seeing it work on your computer.
4
IntermediateExploring Rust syntax basics
🤔Before reading on: Do you think Rust statements end with a semicolon or not? Commit to your answer.
Concept: Learn about Rust's syntax rules like semicolons and comments to write correct code.
In Rust, most instructions end with a semicolon ; to mark the end. For example: println!("Hello, world!"); Comments start with // and are ignored by the computer: // This is a comment These rules help the compiler understand your code.
Result
You write code that the Rust compiler accepts without errors.
Knowing syntax rules prevents simple errors and helps you read other Rust code easily.
5
AdvancedUsing Cargo for project management
🤔Before reading on: Do you think Cargo only compiles code or does it also help manage dependencies and build settings? Commit to your answer.
Concept: Learn how Cargo simplifies building, running, and managing Rust projects and their dependencies.
Cargo is Rust's official tool to manage projects. It creates folders, handles compiling, runs tests, and downloads libraries your code needs. To start a project: cargo new my_project cd my_project cargo run Cargo keeps your project organized and makes building easier.
Result
You can create and manage Rust projects efficiently with one tool.
Understanding Cargo is key to working on real Rust projects beyond simple files.
6
ExpertHow Rust ensures safety from the start
🤔Before reading on: Do you think Rust's compiler checks for memory errors even in a simple program? Commit to your answer.
Concept: Learn how Rust's compiler enforces safety rules even in the first program to prevent bugs and crashes.
Rust's compiler checks your code for mistakes like using memory incorrectly. Even a simple program goes through these checks. For example, it ensures you don't use variables before defining them or forget to handle errors. This safety is built into the language design and compiler.
Result
Your first Rust program is safe and free from common bugs by default.
Knowing that safety checks start immediately helps you trust Rust and write better code from day one.
Under the Hood
When you write a Rust program, the compiler reads your code starting at the main function. It translates your instructions into machine code the computer understands. The println! macro expands into code that calls system functions to display text. The compiler also runs safety checks to prevent errors like invalid memory access before creating the executable.
Why designed this way?
Rust was designed to combine speed and safety. Starting with a clear entry point (main) and using macros like println! makes code readable and efficient. The compiler's strict checks prevent bugs early, avoiding crashes and security issues common in other languages. This design helps developers write reliable software without sacrificing performance.
┌───────────────┐
│ Rust Source   │
│ Code (main)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Rust Compiler │
│ - Parses code │
│ - Checks safety│
│ - Expands macros│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Machine Code  │
│ Executable    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Operating     │
│ System runs   │
│ program       │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Rust run your code directly like a script without compiling? Commit to yes or no.
Common Belief:Rust code runs immediately without compiling, like scripting languages.
Tap to reveal reality
Reality:Rust code must be compiled into an executable before running; it is not interpreted.
Why it matters:Expecting immediate execution can confuse beginners and cause frustration when commands fail without compilation.
Quick: Is println! a regular function in Rust? Commit to yes or no.
Common Belief:println! is a normal function you can call like any other.
Tap to reveal reality
Reality:println! is a macro, which means it works differently and can do things functions cannot, like handling variable arguments.
Why it matters:Misunderstanding println! can lead to confusion about syntax and error messages.
Quick: Does Rust allow missing semicolons at the end of every statement? Commit to yes or no.
Common Belief:You can leave out semicolons at the end of any statement in Rust.
Tap to reveal reality
Reality:Most statements require semicolons; missing them causes compiler errors except for the last expression in a block.
Why it matters:Missing semicolons is a common beginner error that stops code from compiling.
Quick: Does the Rust compiler only check for syntax errors, not safety issues? Commit to yes or no.
Common Belief:The compiler only checks if the code looks right, not if it is safe to run.
Tap to reveal reality
Reality:Rust's compiler enforces strict safety rules to prevent bugs like memory errors before running the program.
Why it matters:Ignoring compiler safety checks can lead to unsafe code and bugs in other languages; Rust prevents this early.
Expert Zone
1
Rust's main function can return a Result type to handle errors gracefully, not just () (unit).
2
The println! macro uses Rust's powerful formatting syntax, which supports complex data display beyond simple text.
3
Cargo manages not only builds but also dependencies, testing, and documentation, making it a full project manager.
When NOT to use
For very small scripts or quick tasks, using Rust might be overkill compared to scripting languages like Python or Bash. Also, if you need rapid prototyping without compilation delays, interpreted languages may be better.
Production Patterns
In real projects, the first program evolves into modules and libraries. Cargo workspaces manage multiple packages. Developers use continuous integration to compile and test Rust code automatically, ensuring safety and correctness.
Connections
Compiled vs Interpreted Languages
Rust is a compiled language, unlike interpreted languages like Python.
Understanding compilation helps grasp why Rust programs need building before running, affecting speed and safety.
Memory Safety in Systems Programming
Rust enforces memory safety at compile time, unlike many systems languages.
Knowing Rust's safety model helps appreciate how it prevents bugs common in low-level programming.
Project Management Tools
Cargo in Rust is similar to npm in JavaScript or Maven in Java.
Recognizing Cargo's role helps understand how modern languages manage code, dependencies, and builds.
Common Pitfalls
#1Trying to run Rust code without compiling first.
Wrong approach:cargo run main.rs
Correct approach:cargo run
Root cause:Misunderstanding that Cargo manages the build process and does not take source files as direct arguments.
#2Omitting semicolon after println! statement.
Wrong approach:fn main() { println!("Hello, world!") }
Correct approach:fn main() { println!("Hello, world!"); }
Root cause:Not knowing Rust requires semicolons to end most statements.
#3Using println without exclamation mark.
Wrong approach:fn main() { println("Hello, world!"); }
Correct approach:fn main() { println!("Hello, world!"); }
Root cause:Confusing macros with functions and missing the ! syntax.
Key Takeaways
Every Rust program starts with a main function where execution begins.
The println! macro is used to print messages to the screen and requires an exclamation mark.
Rust code must be compiled before running, using tools like rustc or Cargo.
Semicolons are important to end statements and avoid compiler errors.
Rust's compiler enforces safety checks even in simple programs to prevent bugs early.