Skip to content

Rust Syntax

Now that you can run Rust, let’s slow down and look at what each part of a program actually means. We’ll use the smallest possible example and take it apart piece by piece.

fn main() {
println!("Hello, World!");
}
▶ Try it Yourself
fn main() {
// your code runs here
}

Every Rust program starts at a function called main. When you run your program, Rust looks for main and runs the code inside it.

  • fn is the keyword for defining a function (a named block of code).
  • main is the function’s name — this specific name is special; it’s the entry point.
  • () holds the function’s inputs (empty here — main takes none).
  • { } curly braces wrap the body — the code that belongs to the function.

Inside the body, each instruction is usually a statement, and statements end with a semicolon ;:

fn main() {
let x = 5;
let y = 10;
println!("{}", x + y);
}

Output:

15

Leaving off a semicolon where one is expected is one of the most common beginner errors — and the compiler will point right at it.

Look closely at println! — that exclamation mark isn’t a typo. The ! means it’s a macro, not a regular function.

You don’t need to fully understand macros yet. Just know this: when you see !, it’s a macro. For now the only one you’ll use is println! for printing text.

fn main() {
println!("This is a macro call");
}

Inside println!, curly braces {} are placeholders that get filled in with values you pass after the text:

fn main() {
let name = "Ferris";
let age = 10;
println!("{} is {} years old", name, age);
}

Output:

Ferris is 10 years old
▶ Try it Yourself

You can also put the variable name directly inside the braces, which is often cleaner:

println!("{name} is {age} years old");

Rust doesn’t care about indentation the way Python does — it uses the curly braces { } to know where blocks begin and end. Indentation is just for humans to read the code more easily.

That said, the community has a standard style, and Rust ships a tool to enforce it automatically:

Terminal window
cargo fmt

Running cargo fmt reformats your code to the official style. Get in the habit of using it.

You can leave notes in your code that Rust ignores. These are comments, and they start with //:

fn main() {
// This is a comment — Rust skips it
println!("Hello!"); // comments can go at the end of a line too
}

We cover comments in more detail on the next page.

  • Every program starts in the main function.
  • Code lives inside curly braces { }; most statements end with ;.
  • A ! (like in println!) means it’s a macro.
  • {} inside println! are placeholders filled by the values you pass.
  • Indentation is for readability — run cargo fmt to auto-format.