Rust Syntax
Rust syntax is the set of rules for writing Rust code. Curly braces { } group lines of code together.
Every program starts in main
main is where Rust begins. The lines inside the braces run, top to bottom:
fn main() { println!("Hello!"); }A statement ends with a semicolon
A statement does an action. The semicolon says: this action is finished:
let x = 3;
let y = x + 1;
println!("y = {}", y);A block can give back a value
Leave the semicolon off the last line of a block. That line's value then becomes the value of the whole block:
let y = {
let x = 10;
x + 5
};
println!("y = {}", y);Spaces are for people
Rust ignores extra spaces and line breaks, so this whole program could live on one line. It would work — but nobody could read it:
fn main(){println!("Hello, Rust!");}Example
fn main() {
let y = {
let x = 3;
x + 1
};
println!("The value of y is {}", y);
}Key points
- Take x + 1 on its own line and end it with a semicolon.
- It is now a statement.
- It runs, and its value is thrown away.
- It changes nothing.
In this example, the block { let x = 3; x + 1 } is used as a value. First, x is set to 3. The last line, x + 1, has no semicolon, so it becomes the value of the block: 4. That value is saved in y. The println! then prints y, so you see 4. If you added a semicolon after x + 1, the block would give back nothing, and the code would not compile.
Note
A semicolon turns an expression into a statement and throws its value away.
This is different from many languages, and it matters a lot in Rust.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
A block's last line ends with a semicolon. What does the block give back?