type
status
date
slug
summary
tags
category
icon
password
Syntax of Rust
Don’t worry, this will be very easy at the beginning. (Really?)
Function goes first
- Similar to C and C++, there must be a
mainfunction as the entry point of the program.
- Use
fnto declare a function, so concise.
- Use
()for receiving parameters, and{}for the actual logic inside the function.
- Remember to use
;to end a statement. As I said, it’s similar to C and C++.
- Example:
A complete structure of function head in Rust should be:
Define variables
- You must use
letto create a variable. let myVar = 3;let myVar: u32 = 3;→ Explicitly specifies the type of the variablemyVarasu32.u32is a 32-bit unsigned integer type in Rust.let mut myVar = 3;→ Creates a mutable variable.
- What? Mutable?
- Variables in Rust are immutable by default.(Its value is determined after compilation.)
- It's important to understand that in Rust,
some_variable = some_valueis not just assigning a value, but rather binding the value to the variable. - This topic is related to Rust’s Ownership feature, which we will discuss in the next post.
- Here's an example:
- If you understand that variables are bound to values, it becomes easier to grasp variable destructuring:
- Basically, destructuring means extracting values from patterns.
- You can also use
constto define a constant value: const MY_CONST_VALUE: i32 = 5;- Constants must always have a type annotation, unlike regular variables.
Statement and expression
- In short:
- Interesting facts:
- In
let x = 1; xis an expression1is an expressionlet x = 1;is a statement- Bound
- Lastly, if an expression doesn’t return anything, it returns
() ()is both a type and a value, and the value is().- You can treat the
()as a(), yes, that is it.
- 作者:Parker Chen
- 链接:www.parkerchenca.com/article/241f0ccf-d7f8-81b0-9868-c92e0985b6d0
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
