In Rust, semicolons are not optional; they are required. They indicate the end of an expression and the start of the next expression, similar to many other programming languages (such as C, C++, and Java).
In Rust, semicolons primarily distinguish statements from expressions. Almost everything in Rust is an expression and returns a value; however, adding a semicolon after an expression converts it into a statement with a return value of the unit type ().
Here is a simple example to illustrate this:
rustfn main() { let x = 5; let y = { let x_squared = x * x; let x_cube = x_squared * x; x_cube + x_squared + x // Note that there is no semicolon here }; // The semicolon here is required to end the let statement println!("y's value is: {}", y); }
In this example, the value of y is computed by a block expression. Within this block, the last expression x_cube + x_squared + x has no semicolon, indicating it is the return value of the block. If a semicolon were added after this expression, the block would return the unit type () instead of the expression's value, which is typically undesired.
In summary, if you want an expression's value to be used as a return value or assigned to another variable, do not add a semicolon after it. If your goal is to execute an operation without caring about the return value, then add a semicolon after the expression.