Sage-Code Laboratory
index<--

Rust Syntax

Rust is a curly braced free form language. It has similar syntax rules as C language. Basic syntax elements may be very familiar to you if you have study C or any other curly braced language.

Page Bookmarks

Syntax Rules

Example:
/* program entry point */
fn main() {
    println!("Hello, world!"); //macro
}

Notes: In this example "fn" is a keyword that define a function. Notation println!() represent a "macro" not a method or function as you may think. Symbol "!" is used to signal that we use a macro that we can call like we call a function.

Basic Elements

There is no better time than now to introduce you the basic concepts and notations of Rust syntax. We will show you on example then we make notes to explain the concept. We explain them as simple as possible so you can learn Rust as your first programming language.

Comments

Code Block

In Rust there is a concept of code block. It is a compact region of code separated by squiggly brackets: {....}. In other languages we start a block using "begin" and terminate with "end" keywords. Having brackets used as block of code makes Rust a little bit harder to understand, but we know how to use spaces and new lines to organize our code.

Indentation

In Rust the indentation is not relevant but recommended. What is relevant is that we can have nested blocks of code. The outer block can contain one or more inner blocks. Each block of code define a local scope.

Variables

The variable declaration in Rust is done using keyword "let" and symbol "=". Once a variable is initialized we call this "binding". So a variable is bound to it's value. A variable that is not bound can't be used. To declare a type for a variable we use symbol ":" after the variable name.

A variable is an identifier or a name that can start with "_" or any alphabetic character but not a special character or a number. So this is almost like any other language.To make a variable mutable we declare it using additional keyword "mut". If you forget this, your variable is actually a constant.

Examples:

/* define variables */
let x: i32 = 5;
let mut y: i32 = 10;
y = 15; //now we can use assignment
x = 15; //this will not work since x is immutable

The assignment operator "=" works only with variables that are mutable and bound to initial value. In this case we can change the value of the variable. So you see there is a difference between "let" that initialize a variable and "=" that assign a value to a variable.

Public Elements

The following conventions are used in Rust for public elements:

Here is an example of a public element that follows these conventions:


pub struct MyStruct {
    // Public field
}

// Public method
impl MyStruct {
    pub fn do_something(&self) {
        // Do something
    }
}

Operators

Rust has ASCII operators. Most operators are single character. Some operators are groups of two characters or 3 characters side by side, with no space between them.

Assign Operators

Assign operators are used in statements, to create new value for a variable. Some operators modify the variable. These are called modifiers.

Operator Description
= Assigns the value on the right to the variable on the left.
+= Assigns the value on the right to the variable on the left, and then adds the value on the right to the variable.
-= Assigns the value on the right to the variable on the left, and then subtracts the value on the right from the variable.
*= Assigns the value on the right to the variable on the left, and then multiplies the value on the right by the variable.
/= Assigns the value on the right to the variable on the left, and then divides the value on the right by the variable.
%= Assigns the value on the right to the variable on the left, and then performs the modulo operation on the value on the right and the variable.
<<= Assigns the value on the right to the variable on the left, and then shifts the value on the right by the number of bits specified on the left.
>>= Assigns the value on the right to the variable on the left, and then shifts the value on the right by the number of bits specified on the left, but in the reverse direction.
>>= Assigns the value on the right to the variable on the left, and then shifts the value on the right by the number of bits specified on the left, but in the right direction.

Numeric Operators

Numeric operators are usually binary. Require left and right operands. In expressions, operators have priority. Multiplication and division first, the addition and subtraction.

Operator Description Example
+ Addition 1 + 2 = 3
- Subtraction 3 - 1 = 2
* Multiplication 2 * 3 = 6
/ Division 6 / 2 = 3
% Modulus 6 % 2 = 0
<< Left shift 1 << 2 = 4
>> Right shift 2 >> 1 = 1
bitwise AND 1 & 2 = 0
| bitwise OR 1 | 2 = 3
~ bitwise NOT ~1 = -2
^ bitwise XOR 1 ^ 0 = 0

Logic operators

Next, you can review all the logic and relation operators of Rust language with expression example. All these expressions are called Boolean expressions.

Operator Description Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
| XOR a | b
< Logical less than a < b
> Logical greater than a > b
== Logical equal to a == b
!= Logical not equal to a != b
?: ternary operator

Delimiters

These are ASCII characters or group of two characters used to separate identifiers or literals. Parenthesis can group elements together in collections or complex expressions.

Symbol Description
: define type
; statement separator, define array element type
, enumeration
. dot operator or decimal separator
\ string continuation or escape code
-> define result type
> relation operator: greater then
< relation operator: less then
// single line comment (can be used at start of line or end of line after ";"
/*...*/ block comment. Other variations: /** .... */ or /*! .... */ each with slightly different purpose.
& borrow
* raw pointer
.. range of numbers or update operator for struct literals
-> define result type of a function
@ pattern bindings
_ ignored
? error propagation symbol
=> used in match patterns
... inclusive range pattern
[...] array literal, vector literal
{...} block of code, struct literal, interpolation placeholder
(...) tuple, expression, parameters
<...> declare generic data types
# meta (compiler directive)
$ macro substitution
:: file based scoping operator similar to "."
m! macro notation for example: print!(). It is also used as logical operator. Do not confuse the two.
'...' character literal
"..." delimiters for string literal

Keywords

In the Rust programming language, there are a number of reserved keywords that cannot be used as identifiers. Keywords are part of the syntax and have special meaning in the language. This table lists all of the reserved keywords in Rust along with their descriptions.

Keyword Description
as Used for type casting or renaming imports in modules
break Used to exit a loop or switch statement
const Used to define a constant value
continue Used to skip the current iteration of a loop
crate Used to specify a crate root module in a codebase
else Used to provide an alternate path in an if statement
enum Used to define an enumeration
extern Used to indicate an external item or linkage
false Boolean value indicating false
fn Used to define a function or closure
for Used to iterate over collections or ranges
if Used to conditionally execute code
impl Used to implement traits or methods for a type
in Used to test if a value is contained in a collection
let Used to bind a value to a variable
loop Used to repeatedly execute a block of code until a condition is met
match Used for pattern matching with an expression
mod Used to define a module
move Used to move ownership of variables between scopes or closures
mut Used to define a mutable variable
pub Used to denote a public visibility modifier
ref Used to introduce a reference to a value
return Used to return a value from a function or closure
self Used to refer to the current module or implementation
static Used to denote a static lifetime or mutable global variable
struct Used to define a structure
super Used to refer to the parent module or implementation
true Boolean value indicating true
trait Used to define a trait or interface
type Used to define a type alias or synonym
unsafe Used to denote unsafe code or operations
use Used to introduce a path to a module or item
where Used in function signatures to specify trait bounds on generic types
while Used to repeatedly execute a block of code while a condition is met
Warning: You should avoid using these keywords as identifiers or file names. Reserved keywords are used in language statements. You do not have to memorize all of them right now. You will learn these in the future from our tutorial.

Read next: Data Types