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
main
function as the entry point of the program.
- Use
fn
to 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
let
to create a variable. let myVar = 3;
let myVar: u32 = 3;
→ Explicitly specifies the type of the variablemyVar
asu32
.u32
is 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_value
is 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
const
to 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;
x
is an expression1
is 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.
- Author:Parker Chen
- URL:www.parkerchenca.com/article/243ef4ab-37c7-45b6-94f8-ba88ef39b5cf
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!
Relate Posts