Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 132 ยท Getting Started

Rust Syntax

Learn the shape of Rust code - items, statements and expressions, the missing-semicolon rule, blocks, naming conventions, attributes and how to read compiler error codes.

Rust syntax looks familiar if you have used C, Java or JavaScript: curly braces, semicolons, if and while. Underneath, though, Rust is built on one idea that most of those languages only half follow: almost everything is an expression, something that produces a value. Once you see this, a handful of rules that confuse beginners (the semicolon at the end of a function, if without a ternary operator, blocks that return values) all make sense together.

This lesson explains the building blocks of a Rust file: items, statements and expressions, the "last expression" rule, blocks, names and naming conventions, attributes, and how to read the compiler's error output. The previous lesson showed what the compiler does with your file; here you learn how to write one it likes.

Items: the top level of a file

A Rust source file is a list of items. An item is a named, permanent declaration: a function (fn), a struct, an enum, a trait, a constant, a module and so on. Items can appear in any order in the file, because the compiler reads them all before it checks anything. You can call a function above the place where you define it.

Rust Items in any order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

main calls build_message before its definition appears, and that is fine. Items can also be nested inside functions (a helper function inside another function, for example), and they are then visible only there. Code that runs, such as let statements and calls, can live only inside function bodies. At the top level you declare; you do not execute.

Statements and expressions

Inside a function body you write statements, and statements are built from expressions. The difference is simple:

  • An expression evaluates to a value: 2 + 3, x * 4, foo(7), if a { 1 } else { 2 }, { ... }.
  • A statement performs an action and does not produce a value you can use. Rust has just two kinds that matter: let statements (declare a variable) and expression statements (an expression followed by ;).

Putting a semicolon after an expression turns it into a statement and throws its value away. This is the whole secret of the semicolon. Compare:

Rust Semicolons throw values away

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The line a + b; compiles, but the compiler prints a warning that the result of the addition is not used (warning: unused arithmetic operation that must be used). The program works; the warning exists because computing a value and dropping it is almost always a mistake. A call to println!(...) ends in a semicolon for a different reason: the macro produces (), the "nothing" value, so there is nothing worth keeping.

The last expression is the value of a block

A block { ... } is itself an expression. Its value is the value of the last expression in it, if that expression has no semicolon. That is how functions return values without a return keyword:

Rust Blocks that produce values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Three expressions here return a value through the "last expression" rule: the body of square, the plain block assigned to label, and both arms of the if. Because if is an expression, Rust has no ternary ?: operator; you do not need one. Note that width and height exist only inside the block. Variables live in the scope of the block that declares them.

The classic mistake: one semicolon too many

If you add a semicolon to that last line, the block's value becomes (), and a function promising to return i32 no longer does. The compiler spots it and tells you exactly what to remove:

Rust A stray semicolon (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0308]: mismatched types: the compiler underlines the return type i32 with expected i32, found ()``, notes that the function "implicitly returns () as its body has no tail or return expression", and points at the semicolon with remove this semicolon to return this value. Delete the semicolon and the program prints 42. You will do this fix many times in your first weeks; after that you will do it before the compiler tells you.

return also exists, and you use it for early exits, such as return Err(...) from the middle of a function. For the final value, idiomatic Rust leaves out return and the semicolon.

Naming conventions

Rust has firm naming conventions, and the compiler even warns when you break them. Following them makes your code instantly readable to every other Rust programmer.

Kind of name Style Examples
Variables, functions, methods, modules, files snake_case user_count, read_file, my_module
Types, traits, enum variants PascalCase (also called UpperCamelCase) Vec, HashMap, Iterator, NotFound
Constants and statics SCREAMING_SNAKE_CASE MAX_SIZE, PI
Generic type parameters short PascalCase, often one letter T, K, V, Item
Lifetimes short lowercase with a quote 'a, 'static

Identifiers may contain letters, digits and underscores, and may not start with a digit. Names starting with an underscore, like _unused, tell the compiler "I know I do not use this" and silence the unused-variable warning. A lone _ is a pattern that ignores a value entirely.

Rust A naming warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Without the #[allow(non_snake_case)] line the compiler would print warning: function Total_Price should have a snake case name, suggesting total_price. The line is an attribute, the next topic. Use it only when you have a reason, such as matching a name from another system.

Attributes

An attribute is metadata attached to the item that follows it. It is written #[...], or #![...] (with a bang) when it applies to the whole enclosing item, such as the whole file. You will see these all the time:

  • #[derive(Debug, Clone, PartialEq)] asks the compiler to generate trait implementations for a struct or enum.
  • #[allow(unused)], #[warn(...)] and #[deny(...)] control lints (see comments and docs).
  • #[test] marks a function as a test, #[cfg(...)] includes code only in certain configurations (attributes and cfg).
  • #[must_use] makes the compiler warn if a function's result is ignored.
Rust derive and Debug printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Without #[derive(Debug)] the {a:?} line would not compile, because Point would not know how to be shown for debugging. The attribute writes that code for you. Structs and traits explain why.

Other things you will see everywhere

A few more syntax features show up in the next lessons, so here is a quick orientation:

  • Type annotations use a colon after a name: let age: u32 = 30; and fn add(a: i32, b: i32) -> i32. The arrow -> introduces the return type. A function with no -> returns ().
  • Paths use :: to reach into modules and types: std::collections::HashMap, String::new(). A dot calls a method on a value: name.len().
  • Macros end with !: println!, vec!, format!, panic!, assert_eq!. They can be called with (), [] or {}; convention is () for most and [] for vec!.
  • References are written with &: &name borrows, &mut name borrows mutably, and * follows a reference. See borrowing.
  • Strings in double quotes are &str. Single quotes make a char: 'a'. Raw strings like r"C:\temp" or r#"say "hi""# skip escaping.
  • Numeric literals may include underscores for readability, 1_000_000, and suffixes, 42u8, 3.5f32.
  • Comments begin with //. See comments and docs.

Whitespace carries no meaning except to separate tokens, but the community uses one layout: four spaces of indent, trailing commas in multi-line lists, and a tool called rustfmt to apply it. You can run cargo fmt and never argue about style again (see Clippy and fmt).

Reading compiler errors

Every serious Rust learner becomes an expert reader of compiler output. A typical diagnostic has these parts:

TEXT
error[E0384]: cannot assign twice to immutable variable `count`
 --> main.rs:4:5
  |
2 |     let count = 1;
  |         ----- first assignment to `count`
3 |     println!("{count}");
4 |     count = 2;
  |     ^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut count = 1;
  |         +++
  • The first line holds the severity (error or warning), the code in brackets (E0384), and a one-sentence summary.
  • The --> line gives the file, line and column where it starts.
  • The gutter shows the code with carets ^^^ under the primary problem and dashes --- marking related places, each with a short label.
  • help: shows a concrete suggestion, often as a diff with + and ~ marks. note: gives extra context.
  • The last line often says For more information about this error, try rustc --explain E0384``.

Run the same mistake yourself:

Rust Assigning to an immutable variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read it from the top: the code is E0384, the arrow points at line 4, and the help suggests let mut count = 1;. Apply that and it works. The recipe for any error is: read the first line, look at the highlighted code, read the help, fix, recompile. And remember that one root mistake can cause several errors; fix the first, rebuild, and many of the others disappear. The compiler errors reference lists the common codes.

Compiler suggestions are usually right, but they are guesses about your intent. Read them before accepting them. A suggested .clone() or an extra & might make the error disappear while hiding a design problem that you will understand better after the ownership lessons.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the value of this block?

    let v = { let a = 2; a * 3 };

    The last expression of a block, written without a semicolon, is the block's value. So a * 3 evaluates to 6 and v is 6.
  2. 2. A function is declared fn f() -> i32 and its body is { 5; }. What does the compiler say?

    5; is an expression statement and the block therefore evaluates to (). The compiler reports mismatched types and suggests removing the semicolon.
  3. 3. Which naming is idiomatic for a constant?

    Constants and statics use SCREAMING_SNAKE_CASE. Variables and functions use snake_case, and types use PascalCase.
  4. 4. What does let ternary = if ok { 1 } else { 0 }; show about Rust?

    if/else is an expression. Both branches must produce the same type, and the chosen branch's value becomes the value of the whole if.
  5. 5. In an error message, what does the --> line tell you?

    The arrow points to file:line:column. The code excerpt below it shows the problem, and help lines suggest fixes.

Summary

  • A file is a list of items (functions, structs, constants, ...) that may appear in any order; code that runs lives inside function bodies.
  • Expressions produce values; a trailing semicolon turns an expression into a statement and discards the value.
  • A block's value is its last expression without a semicolon, which is how functions, if and plain blocks return values. There is no ternary operator.
  • A stray semicolon at the end of a function body gives E0308; delete it.
  • Use snake_case for variables and functions, PascalCase for types and traits, and SCREAMING_SNAKE_CASE for constants. A leading underscore silences unused warnings.
  • Attributes such as #[derive(...)] and #[allow(...)] attach metadata to the next item.
  • Compiler errors have a code, a location, highlighted code and usually a help suggestion; read from the top and fix the first error first.

Next: Cargo, Projects and Crates