This lesson introduces the essential syntax patterns you will use in everyday Rust code. You will learn how variables and mutability work, how to write type annotations, how functions return values, and how Rust uses if expressions, loops, and simple pattern matching. This page focuses on syntax fundamentals only, so deeper topics like ownership, borrowing, error handling, and advanced pattern matching are covered in other lessons.
Rust Syntax Basics
Learn the core Rust syntax you need to read, write, and understand simple programs with confidence.
Start LearningWhat Rust Syntax Basics Covers
Core Syntax Building Blocks
Variables and Mutability
Rust variables are immutable by default, which helps make code easier to reason about. Use mut when you need a value to change after it is created.
Data Types and Annotations
Rust is a statically typed language, so values have a known type at compile time. You can let the compiler infer types in many cases, or add explicit annotations when clarity matters.
Functions and Return Values
Functions are defined with fn and can take parameters with typed inputs. The last expression in a function becomes its return value unless you use an explicit return.
If Expressions and Control Flow
In Rust, if is an expression, so it can produce a value. Combine if with boolean conditions to create straightforward branching logic.
Loops and Pattern Matching
Rust supports loop, while, and for for repeating work in different ways. Basic match expressions let you compare values against patterns and choose the appropriate branch.
Rust Syntax Questions
Do I need to write type annotations in Rust?
Not always. Rust often infers types for you, but explicit type annotations are useful when the code would otherwise be unclear.
Why are variables immutable by default?
Immutability helps reduce accidental changes and makes programs easier to understand. When you need a variable to change, mark it with mut.
How do functions return values in Rust?
A function returns the value of its final expression unless a semicolon is added. You can also use return for an early exit when needed.
Is if a statement or an expression in Rust?
if is an expression in Rust, which means it can evaluate to a value and be assigned to a variable.
What is the difference between loop, while, and for?
loop repeats indefinitely until you break out, while repeats as long as a condition stays true, and for iterates over a sequence of values.
What is basic pattern matching used for?
Basic match expressions help you branch on a value by comparing it against patterns. They are useful for clean, readable control flow.
Next Steps After Syntax Fundamentals
Once you are comfortable with Rust syntax basics, you will be ready to explore how Rust organizes data and program structure in more depth. A strong grasp of variables, types, functions, and control flow makes it much easier to move on to related topics and write practical Rust code with confidence.