Syntax in Rust can be divided into two categories: statements and expressions. Statements are operations to be performed and expressions that have negative effects. Expressions are primarily used to evaluate.

Statements can be divided into two types: Declaration statements and Expression statements. * Declaration statements are used to declare various language items, including declaring variables, static variables, constants, structures, functions, etc., and introducing packages and modules through extern and use keywords. * Expression statements, especially expressions that end in a split. The evaluation of such expressions is discarded and the unit type () is always returned.

Extern create STD; // extern create STD; // use std::prelude::vl::* fn main () { pub fn answer () -> () { let a = 40; let b = 2; assert_eq! (sum(a, b), 42); } pub fn sum(a: i32, b: i32) -> i32 { a + b } answer(); }Copy the code

The first and second behavior declarations are not required for job hunting and are simply used to introduce the standard library package and prelude module. Note this because Rust automatically imports the library module for each Crate, unless the #[no_std] attribute indicates that the library is not needed.

The fn keyword defines two functions answer and sum. The keyword fn is short for function.

The answer function has no input parameter and returns a unit type (). A unit type has a unique value, which is itself, called a unit value for descriptive purposes. The unit value is used as the return value, indicating that the current function has no return value. A function with no return value does not need to declare its return type.

Two variables, A and B, are declared in answer using let and must be followed by a semicolon.

assert_eq! Is a macro statement, which is an assertion provided by Rust that allows you to determine whether two given expressions are evaluated the same. In order to! Statements that end and can be called like functions are called macros in Rust.

Both input parameters and return values of the function sun are specified as type I32. The function body contains only one expression that evaluates the values of a and b and returns them.

When the Rust compiler parses code, if it encounters a semicolon, it continues; If a statement is encountered, the statement is executed; If an expression is encountered, the expression is evaluated, and if there is nothing after the semicolon, the unit value () is appended.

You can think of everything in Rust as an expression. Rust statements can be thought of as special expressions that evaluate to () because of the nature of automatically replenishment of cell values when nothing is available. For a normal expression, you get a normal evaluation.