← Back to Rust Course | Chapter 1: Setup & Basics | Lesson 3 of 7

Your First Rust Program

Your first Rust program is a tiny set of instructions that tells the computer to print words on the screen.

The main Function

Every executable Rust program must have a function named main. This is the entry point: when you run the compiled program, execution starts at the first line inside main and proceeds top to bottom.

Example: The main Function

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

Printing with println!

println! is a macro, not a regular function -- that is why it ends with an exclamation mark. It prints its argument to standard output followed by a newline character, making it the most common way to see output from a Rust program.

Note: Macros like println! can accept a variable number of arguments, which regular Rust functions cannot do.

Example: Printing with println!

markup
fn main() {
    println!("This line has a newline after it");
    println!("So this prints on a new line");
}

Compiling and Running

You turn Rust source code into a runnable program with the rustc compiler, which produces a native executable. You then run that executable directly from the command line.

Example: Compiling and Running

bash
rustc main.rs
./main

⚠️ Run this command in your terminal.

Statements End With Semicolons

Most lines of code inside a Rust function are statements, and Rust requires each one to end with a semicolon. Forgetting a semicolon is one of the most common early compiler errors.

Example: Statements End With Semicolons

markup
fn main() {
    let message = "Semicolons separate statements";
    println!("{}", message);
}
Common Mistakes
  1. Forgetting the semicolon at the end of a statement, which Rust requires unlike some scripting languages.
  2. Naming the file something other than what you pass to rustc, then wondering why the compiler can't find it.
  3. Forgetting that main is the required entry point function name -- Rust always starts running from fn main().
Chapter Summary
  • Every Rust program needs a main function, which is where execution begins.
  • println! is a macro (note the !) used to print text followed by a newline.
  • Source files end in .rs and are compiled with rustc filename.rs, producing an executable.
  • Statements in Rust end with a semicolon.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.