Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Syntax

Every language has its grammar, and programming languages are no different. Syntax is simply the set of rules for how code must be written so that the compiler understands it. The good news is that Rust's basic rules are few, and once you have seen a couple of programs they start to feel natural.

Let us take our first program apart, line by line.

fn main() {
    println!("Hello, World!");
}
Output
Hello, World!

fn main: where the program starts

fn is short for function. A function is a named group of steps. main is a special name: when a Rust program starts, it looks for the function called main and runs it. Every program you write needs exactly one main.

The empty round brackets () after the name are where a function's inputs would go. main needs none, so they stay empty. We will write functions with inputs later.

Curly brackets hold the steps

The curly brackets { and } mark the beginning and the end of the function's body: the steps it carries out. Everything between them belongs to main. The lines inside are indented by four spaces. Rust does not require the indentation, but every Rust programmer uses it, because it makes it easy to see what belongs where. The editor indents for you when you press Enter.

Semicolons end statements

A statement is one instruction, and in Rust most statements end with a semicolon ;, like a full stop at the end of a sentence. Forgetting one is the most common beginner mistake, and that is fine: the compiler will tell you exactly where it expected one.

fn main() {
    println!("One statement.");
    println!("Another statement.");
    println!("And a third, all on their own lines.");
}
Output
One statement.
Another statement.
And a third, all on their own lines.

The exclamation mark

You may have noticed that println! ends with an exclamation mark. That is not excitement! It tells you that println! is a macro, not a normal function. A macro is a piece of code that writes more code for you while compiling. For now you only need to remember: when you print, write the !. Without it, Rust looks for a function called println, does not find one, and tells you so.

Practice exercises

  1. Write a program with three println! lines that print your name, your city and your favourite food.
  2. Delete the ! from one println! and read the error. Put it back.
  3. Delete the closing } at the end and see how the compiler points at the opening bracket that was never closed.